[JavaScript] 기초 문법 정리(1)
이 포스팅은 Nomad Coders의 [바닐라 JS로 크롬 앱 만들기]를 수강하고 그 내용을 간단히 정리한 글입니다.
변수 만들기
JS에서는 Camel 표기법을 사용함.
const변수_이름=값: 가장 자주 사용하는 방법. 상수로서 바꿀 수 없는 값.let변수_이름=값: 업데이트(변경) 가능한 변수.var변수_이름=값:let과 동일한 성격을 지님. 옛날 방식이므로 사용을 지양할 것.
값 보이기
- 경고창:
alert(내용) - 콘솔창
console.log(내용)console.dir(객체): 더 자세한 내용을 출력함. 객체가 가지고 있는 값.
자료형
bool, null, undefined
- bool
truefalse: 값이 ‘false’로 존재함
null: 값이 ‘없음’으로 존재함undefined: 변수는 존재하나 그 값이 없음. (ex)let a;로 선언만 하고 값 할당 안 함
NaN(Not a Number): 숫자가 아님
isNaN(값): NaN인지 판단
자료형의 변경
parse계열 함수 (ex) 정수로 변경:parseInt("16");String(): 문자열로 변환- JSON 이용
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]
array
- 선언
const배열_이름=[요소1, 요소2, ...]- 한 배열 내 다양한 자료형 포함 가능. (ex)
const myArray = ["hi", 123, -44, true, null, undefined];
- 값 추가:
배열_이름.push(값); - filter
- 선언:
배열.filter(함수) -
함수가 true인 것만 남겨둔 배열을 반환. inplace가 아님에 주의myArray = [1, 2, 3, 4] newArray = myArray.filter((num) => num <= 3);
- 선언:
함수
- 선언:
function함수_이름(인자){} - arrow function:
(인자) => 내용
function add(a, b) {
return a+b;
}
add(1, 2); // 3
조건문
if (statement1) {
// something
} else if (statement2) {
// something
} else {
// something
}
object
기본
- 선언:
const객체_이름={프로퍼티: 값, 프로퍼티, 값, ...}const로 선언 시에 객체 자체는 바뀔 수 없지만 내부 프로퍼티는 변경 가능
- Property 사용
- 가져오기:
objectName.propertyName - 추가하기:
objectName.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: 특정 객체가 가지고 있는 클래스(속성) 전부
객체.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에서 정의한 내용을 JS 형식으로 보여줌. 즉, JS와 HTML이 연결되어 있다는 의미
- 접근:
document.<HTML_ELEMENT>(ex.document.title) - 변경:
document.<HTML_ELEMENT> = <NEW_VALUE>
window
document처럼 브라우저가 제공하는 오브젝트 중 하나. 브라우저 창에 대한 정보 제공- 예:
resize이벤트,copy이벤트(무언가가 복사됨),offline이벤트(인터넷이 오프라인이 됨) 등이 있음
JS과 HTML 연결
HTML에서 JS 선언하기
<body>
<script src="JS_파일경로"></script>
</body>
HTML element 가져오기
- getElementBy 함수: 일치하는 전부 찾아 배열로 가져옴
document.getElementById("아이디");document.getElementByClassName("클래스명");document.getElementByTagName("태그_종류");
- querySelector 함수: 요소를 CSS 방식으로 검색할 수 있음.
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";
JS에서 HTML로 추가하기
document.createElement("태그"): 이렇게만 선언하면 아직 JS에만 존재할 뿐, HTML엔 없음document.태그.appendChild(만든_요소) 또는prependChild(): HTML 특정 태그의 맨 뒤/앞에 추가
Event
검색창에 “태그 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
- localStorage
- 특정 값을 (key, value) 쌍으로 저장함
- 크롬 기준, [개발자도구 - Application - Local Storage]에서 확인할 수 있음
- 저장하기:
localStorage.setItem(KEY,VALUE); - 가져오기:
localStorage.getItem(KEY); - 삭제하기:
localStorage.removeItem(KEY);
geolocation과 API 사용
-
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(): 내림
댓글은 Disqus 로 제공됩니다.