본문 바로가기

Language/Javascript9

비 구조화 할당 ■ 배열 비 구조화 할당 let arr = ["one", "two", "three"]; const [a, b, c, d = "four"] = arr; // d 는 four 로 기본값 지정 console.log(b); // two console.log(d); // four 배열 비 구조화 할당에서는 인덱스가 기준이 된다. 인덱스 기준이므로 a = one, b = two, c = three 의 값이 할당 된다. ■ 배열 비 구조화 할당 응용 let a = 1; let b = 2; [a, b] = [b, a]; console.log(a, b); // 2 1 ■ 객체 비 구조화 할당 객체 비 구조화 할당에서는 키값이 기준이 된다. 키값이 없는 경우에는 기본값을 설정할 수 있다. let object = { ONE.. 2023. 3. 9.
조건문 업그레이드 ■ 배열 내장 함수를 활용한 조건문 업그레이드 function isCountry(country) { if (country === "USA" || country === "UK") { return true; } else { return false; } } const a = isCountry("USA"); const b = isCountry("Korea"); console.log(a); // true console.log(b); // false 위 조건문을 다음과 같이 변환할 수 있다. function isCountry(country) { if (["USA", "UK"].includes(country)) { return true; } else { return false; } } ■ 객체 괄호 표기법을 활용한 .. 2023. 3. 7.
단락회로 평가 ■ 단락회로 평가 왼쪽에서 오른쪽으로 연산하게 되는 논리 연산자의 연산 순서를 이용한 문법 console.log(false && true); // AND 연산자에서 왼쪽이 false 이면 오른쪽 값은 무시되며 연산을 끝내버리는 것이 단락회로 평가 console.log(true || fasle); // OR 연산자에서는 왼쪽이 true 이면 오른쪽 값은 읽지 않고 연산이 끝나버린다. ■ 단락회로 평가 응용 const getName = (person) => { const name = person && person.name; return name || "객체가 아닙니다."; }; let personA; const a = getName(personA); console.log(a); // 실행결과 : 객체가 아닙.. 2023. 3. 6.
배열 내장 함수 ■ forEach 배열의 모든 요소에 순차적으로 접근하여 콜백 함수 수행 const arr = [1, 2, 3, 4]; // 화살표 함수 arr.forEach((elm) => console.log(elm)); // 함수 표현식 arr.forEach(function (elm) { console.log(elm); }); 실행결과 1 2 3 4 ■ map 배열의 모든 요소에 순차적으로 접근하여 콜백 함수를 수행한 후 새로운 배열로 반환 const arr = [1, 2, 3, 4]; const newArr = arr.map((elm) => elm * 2); console.log(newArr); 실행결과 [2,4,6,8] ■ includes 배열의 요소와 전달 받은 인자가 일치하는지 확인하여 true / fals.. 2023. 3. 5.