JavaScript
1. 페이지를 interactive 하게 만들기 위해!
2. 모든 브라우저에 기본 내장
3. 프론트엔드는 html, css, javascript 밖에 없다.
4. js 역시 css처럼 html 파일에 연결해서 사용한다!<body> <script src="app.js"></script> </body>
나만의 cheatsheet를 만드는게 목적이라 모르는 개념이 아니면 다른 언어와 다른 점만 정리한다!
console.log('콘솔창에 log 찍어줌'); const a = 10; // 상수 let b = 20; // 변수. swift에서는 이게 상수인데......😱
bool true, false; // bool은 소문자. let point = null; // null : 값이 없다고 명시적으로 알려줌, 파이썬 None let something; // undefined : null과 다름😱 변수는 메모리에 있는데, 값이 없는 것
const list = []; // 들어가는 값의 type이 다 달라도 됨...😱 list[3]; list.push(); // push가 기본.😱
// Object : 다른 언어 dictionary 문법....😱 const player = { name: "ddosang", points: 10, update: "true" }; player.name, player["name"] // property에 접근. const여도 안의 property 값은 수정 가능. player.lastName = "Lim"; // 없는 속성 넣으면 새로 속성도 추가됨❗️ player.name.length // string 길이 반환.
- js 는 camelCase 사용한다.
- default로 const를 쓰고 값을 바꿀 일이 있을 때 let으로 바꾼다. 원래는 변수 var만 있었다.
always const, sometimes let, never var.- list, object는 const 여도 안의 요소는 수정 가능. 아예 새로 대입하는 것만 불가능.
📥 function 📤
// function 다 써야됨. 인자 자료형 필요X function sayHello(nameOfPerson, age) { console.log("Hello my name is " + nameOfPerson); } // // object 에 함수 주기 const player = { name: "ddot", sayHello: function(otherPersonName) { return "hello" + otherPersonName } } console.log(player.name); player.sayHello("sooyoung");
- function 인자 1개인데 10개 보내면 앞의 값 부터 인자 개수만큼 알아서 사용
문법만 보면 C랑 엄청 먼데 ; 찍어야하는게 나중에 ; 안 찍어서 오류 엄청 날듯...
🐈conditional🐈⬛
// prompt: 사용자에게 입력 받아옴. 요즘은 안 씀. 직접 모달을 만들어서 쓰자. const age = prompt("How old are you?"); // 항상 string typeof 변수; typeof(변수); parseInt(age); // return 숫자 or NaN (Not a Number) // if(!isNaN(age)) {} else if(age < 18 || age > 50) {} else if(age >= 18 && age <=50) {} else if (age === 121) {} // === 3개.
for문은 C와 같으나, list 나 string에 해당되는 for...of(element), for...in(element 안의 property까지) 같은 문법이 더 있다.
js의 핵심은 HTML을 interactive 하게 만드는 것.
HTML에 적용하기 🧮
document // HTML을 가리키는 Object document.title = "hi"; // const title = document.getElementById("title"); document.dir(title); // element가 가지고 있는 정보들을 잡아옴. ex) onClick, onDrag ... title.innerText = "text"; // h1 내용 바뀐다. // const title = document.getElementsByClassName("hello"); const title = document.getElementsByTagName("h1"); const title = document.querySelector(".hello h1:first-child"); // CSS selector 문법에 해당하는 첫번째 것 딱 하나만 잡아옴. const title = document.querySelectorAll(".hello h1"); // 전부 list로 잡아옴. const title = document.querySelector("h1#hello"); // 이렇게 태그랑 아이디 둘 다 써도 됨. // // style 을 js로 바꿀 수 있다. title.style.color = "blue";
<div class="hello"> <h1 class="hello" id="title">Grab me!</h1> <h1 class="hello">Grab me!</h1> <h1>Grab me!</h1> </div>
Event 🥳
방법1. addEventListener 추가하는 방법// 어떤 event를 감지할 지, event가 감지됐을 때 실행할 함수. // event는 종류가 많으니까 찾아서 쓰자. click, mouseenter, mouseleave, ... function handleTitleClick() { title.style.color = "green"; } title.addEventListener("click", handleTitleClick); // function handelWindowResize() { // body 는 특별하기 때문에 document.body로 가져올 수 있지만, div, h1 같은 것은 안됨. 위에서 사용한 get~~ or querySelector 이용하자. document.body.style.backgroundColor = "tomato"; } window.addEventListener("resize", handleWindowResize);
방법2. onEvent 붙이기
title.onclick = handleTitleClick;
style 을 바꾸는 것은 웬만하면 CSS에서 하자.
js를 최대한 적게 쓰자. 대신 raw String 보다는 변수를 정의해서 쓰자.
element에 class를 추가해서 event 시 style 변경
<h1 class="font">Click Me!</h1>
h1 { color: cornflowerblue; } .clicked { color: pink; } .font { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; }
function handleTitleClick() { h1.classList.toggle("clicked"); }
밑의 js 코드는 모두 같은 동작을 한다.
// 1. 정직하게 style 이용 -> style은 CSS에서 바꾸는게 좋다. // 2번 이상 쓰이면 변수로 만들자. const h1 = document.queryString("h1"); function handleTitleClick() { const currentColor = h1.style.color; let newColor; if (currentColor === "cornflowerblue") { newColor = "pink"; } else { newColor = "cormflowerblue"; } h1.style.color = newColor }
// 2. className 을 바꿔줌 -> 원래 가지고 있던 class가 날아감. const h1 = document.queryString("h1"); function handleTitleClick() { const clickedClass = "clicked" if (h1.className === clickedClass) { h1.className = ""; } else { h1.className = clickedClass; } }
// 3. classList 이용. -> 굿 const h1 = document.queryString("h1"); function handleTitleClick() { const clickedClass = "clicked" if (h1.classList.contain(clickedClass)) { h1.classList.remove(clickedClass); } else { h1.classList.add(clickedClass); } }
// 4. 그치만 우리에게는 토글이 있다!!! function handleTitleClick() { h1.classList.toggle("clicked"); }
// element.querySelector 를 탈 수 있다!!!! const loginForm = document.querySelector("#login-form"); const loginInput = loginForm.querySelector("input"); // input에는 value property가 있다. input에 입력된 값이다. const value = loginInput.value
입력값 검사 : js로 코드를 짤 수도 있지만, HTML 기능을 사용하자.
<input required maxlength="50" type="text">
브라우저가 넘겨주는 첫번째 인자와 preventDefault
function onLoginSubmit(event) { // 인자 이름은 event로 쓰는게 관행. // 해당 event가 일어났을 때, 브라우저가 기본적으로 하는 동작을 막음! event.preventDefalut(); //alert("asdf"); // alert 도 기본 동작을 잠시 멈춤. // 이 뒤로 custom 하면 됨. loginForm.classList.toggle(HIDDEN_CLASSNAME); const username = loginInput.value; // 아래 두 문장의 결과는 같음. greeting.innerText = "Hello " + username; greeting.innerText = `Hello ${username}`; greeting.classList.add(HIDDEN_CLASSNAME); } loginForm.addEventListener("submit", onLoginSubmit);
inner DB - localStorage
localStorage.setItem('myCat', 'Tom'); const cat = localStorage.getItem('myCat'); //tom localStorage.removeItem('myCat');
두 번 이상 반복되는 코드와 문자열은 함수, 변수로 만들어서 사용하자.
interval & timeout
// 인자 : 함수, 간격 ms. setInterval(sayHello, 5000); // interval : 일정 간격으로 일어나는. setTimeout(sayHello, 5000); // timeout : 딜레이를 줌.
Date
js Date timestamp 는 ms 단위.const date = new Date(); date.getFullYear(); date.getMonth(); date.getDay(); date.getHours(); date.getMinutes(); date.getSeconds(); date.getMilliseconds();
// 시계 만들기. function getClock() { const date = new Date(); // padStart(2, "0"); - 어떤 문자열의 길이가 2 이상이면 아무것도 하지 않고, // 2 미만일 때 길이가 2가 될 때까지 앞에 0을 붙임. padEnd도 있다. const hours = String(date.getHours()).padStart(2, "0"); const minutes = String(date.getMinutes()).padStart(2, "0"); const seconds = String(date.getSeconds()).padStart(2, "0"); clock.innerText = `${hours}:${minutes}:${seconds}`; } // 처음 들어갔을때는 출력이 되지 않으므로 한번은 직접 출력해준다. getClock() setInterval(getClock, 1000);
Math
Math.random(); //랜덤 // 반올림, 내림, 올림 Math.round(); Math.floor(); Math.ceil();
js로 element 생성
// HTML 객체를 JS로 생성. const bgImage = document.createElement("img"); bgImage.src = `img/${chosenImage}`; // body에 넣어줌. document.body.appendChild(bgImage); // body맨 뒤에 추가 document.body.prependChild(bgImage);
js로 CSS 속성을 주는 방법
body.style.background = `linear-gradient(${selectedColor1}, ${selectedColor2})`;
const API_KEY = "안알랴줌";
// 2. 정상 실행 시 실행할 함수 function onGeoOk(position) { // 2-1. 성공 시 position을 넘겨주는데 위도와 경도 정보가 담겨있음. let lat = position.latitude; let lon = position.longitude; // 2-2. 위도와 경도 정보를 open weather map API를 이용해서 날씨 정보를 받아올 것임. const url = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${API_KEY}&units=metric`; fetch(url).then(response => response.json()).then(data => { const weather = document.querySelector("#weather span:first-child"); const city = document.querySelector("#weather span:last-child"); weather.innerText = data.name; city.innerText = `${data.weather[0].main} / ${data.weather.main}`; }); //url을 부름. 개발자 도구 네트워크 창에서 확인 가능. }
// 3. 에러 시 실행할 함수 function onGeoError() { alert("Can't find you. No weather for you."); }
// 1. 인자 2개 : 정상 작동 시 실행할 함수, 에러 시 실행할 함수 navigator.geolocation.getCurrentPosition(onGeoOk, onGeoError);