이 포스팅은 Nomad Coders의 [바닐라 JS로 크롬 앱 만들기]를 수강하고 그 내용을 간단히 정리한 글입니다.
JS에서는 Camel 표기법을 사용함.
const 변수_이름 = 값 : 가장 자주 사용하는 방법. 상수로서 바꿀 수 없는 값.let 변수_이름 = 값 : 업데이트(변경) 가능한 변수.var 변수_이름 = 값 : let과 동일한 성격을 지님. 옛날 방식이므로 사용을 지양할 것.alert(내용)console.log(내용)console.dir(객체): 더 자세한 내용을 출력함. 객체가 가지고 있는 값.truefalse: 값이 ‘false’로 존재함null: 값이 ‘없음’으로 존재함undefined: 변수는 존재하나 그 값이 없음. (ex) let a; 로 선언만 하고 값 할당 안 함NaN(Not a Number): 숫자가 아님
isNaN(값): NaN인지 판단
parse 계열 함수 (ex) 정수로 변경: parseInt("16");String(): 문자열로 변환JSON.stringify(객체): 객체(object, array 형)을 string으로 변경JSON.parse(문자열): string 형태의 문자열을 배열/object로 변경
const objStudent = {name: "Jessy", age: 20};
JSON.stringify(student); // '{"name":"Jessy","age":20}'
JSON.parse("[1, 2, 3, 4]"); // [1, 2, 3, 4]
const 배열_이름 = [요소1, 요소2, ...]const myArray = ["hi", 123, -44, true, null, undefined];배열_이름.push(값);배열.filter(함수)함수가 true인 것만 남겨둔 배열을 반환. inplace가 아님에 주의
myArray = [1, 2, 3, 4]
newArray = myArray.filter((num) => num <= 3);
function 함수_이름 (인자) {}(인자) => 내용function add(a, b) {
return a+b;
}
add(1, 2); // 3
if (statement1) {
// something
} else if (statement2) {
// something
} else {
// something
}
const 객체_이름 = {프로퍼티: 값, 프로퍼티, 값, ...}
const로 선언 시에 객체 자체는 바뀔 수 없지만 내부 프로퍼티는 변경 가능objectName.propertyNameobjectName.propertyName = value함수 역시 프로퍼티가 될 수 있음
const student = {
name: "Jane",
age: 15,
sayHello: function(otherName) {
console.log("Hello, " + otherName);
}
};
student.score = 100; // new property
student.sayHello("Jin"); // function property
객체.classList.contains(조사할_클래스): 특정 클래스가 있는가?객체.classList.remove(삭제할_클래스): 특정 클래스를 삭제함객체.classList.add(추가할_클래스): 특정 클래스를 추가함객체.classList.toggle(클래스): 특정 클래스가 없다면 추가하고 있다면 삭제
.clicked{
color: tomato;
}
const h1 = document.querySelector("div.hello:first-child h1");
// 값 직접 대체
function handleTitleClick(){
const clickedClass = "clicked";
if(h1.className === clickedClass){
h1.className = "";
} else{
h1.className = clickedClass;
}
}
// 직접 대체하지 않기: classList
function handleTitleClick(){
const clickedClass = "clicked";
if(h1.classList.contains(clickedClass)){
h1.classList.remove(clickedClass);
} else{
h1.classList.add(clickedClass);
}
}
// toggle 사용하기
function handleTitleClick(){
h1.classList.toggle("clicked");
}
document.<HTML_ELEMENT> (ex. document.title)document.<HTML_ELEMENT> = <NEW_VALUE>document 처럼 브라우저가 제공하는 오브젝트 중 하나. 브라우저 창에 대한 정보 제공resize 이벤트, copy 이벤트(무언가가 복사됨), offline 이벤트(인터넷이 오프라인이 됨) 등이 있음<body>
<script src="JS_파일경로"></script>
</body>
document.getElementById("아이디");document.getElementByClassName("클래스명");document.getElementByTagName("태그_종류");document.querySelector(); 일치하는 제일 처음 하나만 찾음
".클래스명""#아이디""태그"":자식_요소" (ex. first-child, last-child)document.querySelectorAll(); 일치하는 전부를 찾아 배열로 가져옴<div class="hello">
<h1 id="title" class="hello">Hello!</h1>
</div>
// 아래는 모두 동일한 작동을 함
const title = document.getElementById("title");
const title = document.getElementsByClassName("hello");
const title = document.getElementsByTagName("h1");
const title = document.querySelector(".hello h1");
const title = document.querySelector("#title");
const title = document.querySelectorAll(".hello h1");
const title = document.querySelector("div.hello:first-child h1");
title.innerText = "Hi!";
title.style.color = "red";
document.createElement("태그"): 이렇게만 선언하면 아직 JS에만 존재할 뿐, HTML엔 없음document.태그.appendChild(만든_요소) 또는 prependChild(): HTML 특정 태그의 맨 뒤/앞에 추가검색창에 “태그 html element mdn”이라고 검색하고, ‘Web APIs’ 페이지에서 살펴보기
console.dir(요소)시on으로 시작하는 속성이 이벤트에 해당
addEventListener("이벤트", 콜백함수)이벤트_속성 = 콜백함수;function 함수_이름 (이벤트_정보_인자) { 처리 내용 }const title = document.querySelector("div.hello:first-child h1");
function handleTitleClick(){
console.log("title was clicked!");
title.style.color = "blue";
}
function onLoginSubmit(event){
event.preventDefault();
console.log(event);
}
// 아래 두 줄은 동일
title.addEventListener("click", handleTitleClick);
// title.onclick = handleMouseLeave;
event.preventDefualt(): 특정 이벤트의 기본 동작(ex.submit이라면 새로고침)을 발생시키지 않게 함.
localStorage.setItem(KEY, VALUE);localStorage.getItem(KEY);localStorage.removeItem(KEY);navigator.geolocation.getCurrentPosition(정상_작동_시_함수, 비정상_시_함수) : 사용자의 위치 반환
function onGeoOk(position){
const lat = position.coords.latitude; // 위도 37.xxxxxx
const lon = position.coords.longitude; // 위도 126.xxxxxx
}
navigator.geolocation.getCurrentPosition(onGeoOk, onGeoError);
OpenWeatherMap 서비스 API를 사용해 특정 위치의 날씨 정보 받아오기
fetch(URL) : URL을 JS가 대신 불러옴then(): 특정 동작 이후의 응답을 처리함
const url = `https://api.openweathermap.org/data/2.5/weather?lat={위도}&lon={경도}&appid=${API키}`;
fetch(url)
.then((response) = response.json()) // url의 응답을 json으로 가져옴
.then((data) => {
// 특정 처리 수행
});
setInterval(함수, 시간): 매 시간(ms 단위)마다 함수를 수행함setTimeout(함수, 시간): 시간 후 함수를 수행함"문자열".padStart(전체_길이, "채울_문자") 또는 padEnd(): 해당 문자열의 지정 길이만큼 앞이나 뒤에 채울_문자로 채움 (ex. "1".padStart(2, "0");는 01을 반환)Math.random(): (0, 1) 범위의 난수 생성Math.round(): 반올림Math.ceil(): 올림Math.floor(): 내림