공부/JavaScript (9) 썸네일형 리스트형 localStorage 1. localStorage.setItem('key', 'value') 키와 값으로 localStorage에 저장 2. localStorage.getItem('key') 키로 localStroage에서 값 가져오기 3. localStorage.removeItem('key') 키로 데이터 삭제 4. localStorage.key(0) 0번째 키 가져오기 5. localStorage.length 키가 몇개인지 가져오기 구조분해할당 자바스크립트에서는 배열이나 객체에서 값을 가져올 때, 구조분해할당을 통해서 편하게 가져올 수 있다. 이를 활용해서 react등 다른 SPA 프레임워크에서도 정말 많이 쓰인다. # 01. 배열 const food = ["🍕", "🥓", "🍙"]; const [pizza, bacon, rice] = food; console.log(pizza); // 🍕 console.log(bacon); // 🥓 console.log(rice); // 🍙 const pizza = food[0] 이렇게 하나하나 나열하지 않아도, 음식이라는 배열을 구조분해할당을 통해서 각 음식의 변수를 손쉽게 만들 수 있다. function createApple() { return ["apple", "🍎"]; } const [name, emo.. 논리 연산자 (Logical Operator) # 01. 단축평가 (short-circuit evaluation) && 그리고 || 또는 # 02. && Truthy, Falsy 평가 Logical AND (&&) evaluates operands from left to right, returning immediately with the value of the first falsy operand it encounters; 논리 연산자 &&은 왼쪽부터 평가하고 첫번째 falsy를 반환함 if all values are truthy, the value of the last operand is returned. 만약 모든 값이 truthy라면 마지막 truthy를 반환함 ex) console.log("" && "foo"); // "" console.log.. reduce 배열에서 쓸 수 있는 고차함수 # 01. reduce reduce 함수는 빈 요소를 제외하고 배열 내에 존재하는 각 요소에 대해 배정된 콜백함수를 한번씩 실행한다. 이 콜백함수는 아래 4개의 인자를 받는다. 1) 누산기 (acc) 2) 현재값 (cur) 3) 현재 인덱스 (idx) 4) 원본배열 (src) 그리고 initialValue값을 가진다. 구문) arr.reduce(callback[, initialValue]) # 02. 예시 1) 합산하기 const array1 = [1, 2, 3, 4]; // 0 + 1 + 2 + 3 + 4 const initialValue = 0; const sumWithInitial = array1.reduce( (previousValue, currentValue) => previousValue + .. Class - this 바인딩 # 01. 클래스 안의 함수 Class 안의 함수를 인자로 전달할 때 해당 class와 함수를 바인딩 해줘야 정상적으로 작동함. 예시) class Food { constructor(name, emoji) { this.name = name; this.emoji = emoji; body.addEventListener('click', this.onClick); } onClick = (event) =>{ const target = event.target; if(target.matches('#egg')){ this.func && this.func('egg'); }else{ this.func && this.func('food'); } } setClickListener(func){ this.func = func; }.. Truthy & Falsy 조건문 사용시 true로 간주되는 값과, false로 간주되는 값이 있다. # 01. Truthy : 데이터 있음 true, {}, [] , "0", "-0", -27, infinity, -infinity 텅빈 오브젝트, array는 true로 간주된다. # 02. Falsy : 데이터 없음 false, 0, -0, "", '', ``, null, undefined, NaN 텅빈 문자열은 false로 간주된다. async, await # 01. 사용하는 이유 ! - promise는 콜백지옥에서 벗어나 한결 깨끗한 함수형 프로그래밍 코딩을 할 수 있게 도와주지만 .. ! - .then .then .then 을 중첩으로 연결하면 콜백지옥처럼 가독성이 떨어짐 - async, await 을 사용하면 비동기적인 코드를 절차적으로 사용할 수 있게 되어 가독성이 올라감 👍 # 02. 사용 방법 function getId() { return new Promise((resolve) => { setTimeout(() => { resolve('Id1234') }, 1000) }) } function getPassword() { return new Promise((resolve) => { setTimeout(() => { resolve('password1.. Promise # 01. Promise MDN 정의 : The promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value. : Promise 오브젝트는 비동기적으로 완료된 이벤트의 성공 혹은 실패와 그 결과 값을 알려줌 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise Promise는 Callback 지옥에서 벗어나 깔끔한 함수형 프로그래밍을 할 수 있게 도와줌. A Promise is in one of these states: 진행중, 성공, 실패의 3가지 상태값.. 이전 1 2 다음