// 구조 분해 할당 사용
let a = 5, b = 10;
[a, b] = [b, a];
console.log(a, b); // 10 5
// 일반적인 루프 생성
let sum = 0;
for (let i = 5; i < 10; i += 1) {
sum += i;
}
// 함수형 프로그래밍 방식
const sum = Array
// Array.from() 유사배열객체, 반복가능객체를 얕게 복사
// Array.length가 5이고, 값(undefined)은 쓰지 않고(_), 인덱스값(k)만 사용,
.from(new Array(5), (_, k) => k + 5)
// [ k + 5, ..., k + 5 ]
// [0 + 5, 1 + 5, ... , 4 + 5]
// [5, 6, 7, 8, 9]
// Array.reduce(업데이트식, 초기값) 배열을 돌며 모두 더해줌
.reduce((acc, cur) => acc + cur, 0);
// (0, arr[0]) => 5
// (0 + arr[0], arr[1]) => 11
// ...
// (0 + arr[0] + arr[1] + arr[2] + arr[3] arr + [4]) => 35
// 35
const names = ['Lee', 'Kim', 'Park', 'Lee', 'Kim'];
const uniqueNamesWithArrayFrom = Array.from(new Set(names));
const uniqueNamesWithspread = [...new Set(names)];
const person = {
name: 'Jung Kaka',
familyName: 'Jung',
givenName: 'Kaka'
};
const company = {
name: 'Dog',
address: 'Seoul'
};
const leeSunHyoup = { ...person, ...company };
console.log(leeSunHyoup);
// {
// name: 'Jung Kaka',
// familyName: 'Jung',
// givenName: 'Kaka'
// name: "Dog" // 같은 키는 마지막에 대입된 값으로 정해짐
// }
/// ||
// 기본값을 넣어주고 싶을 때 사용
// participantName이 0, undefined, 빈 문자열, null일 경우 'Guest'로 할당됨
const name = participantName || 'Guest';
/// &&
// flag가 true일 경우에만 실행됩니다.
flag && func();
// 객체 병합에도 이용할 수 있습니다.
const makeCompany = (showAddress) => {
return {
name: 'Dog',
...showAddress && { address: 'Seoul' }
}
};
console.log(makeCompany(false));
// { name: 'Dog' }
console.log(makeCompany(true));
// { name: 'Dog', address: 'Seoul' }
const dog = {
name: 'Jung Kaka',
familyName: 'Jung',
givenName: 'Kaka'
company: 'Dog',
address: 'Seoul',
}
const { familyName, givenName } = dog;
// 객체 생성 시 키 생략 가능
// 프로퍼티 키를 변수 이름으로 생략
const name = 'Jung Kaka';
const company = 'Dog';
const dog = {
name,
company
}
console.log(dog);
// {
// name: 'Jung Kaka',
// company: 'Dog.'
// }
// 함수에 객체 넘기기 ({}) =>
// 필요한 것만 꺼내 쓸 수 있는 장점
const makeCompany = ({ name, address, serviceName }) => {
return {
name,
address,
serviceName
}
};
const dog = makeCompany({
name: 'Dog',
address: 'Seoul',
serviceName: 'Snack'
});
// [변수명]: 키 이름을 변수값으로 지정
const nameKey = 'name';
const emailKey = 'email';
const dog = {
[nameKey]: 'Jung Kaka',
[emailKey]: 'kaka@dogmail.com'
};
console.log(dog);
// {
// name: 'Jung Kaka',
// email: 'kaka@dogmail.com'
// }
// !! 연산자
// false: 0, null, 빈 문자열, undefined, NaN
// true: 그 외
function check(variable) {
if (!!variable) {
// variable이 true면
console.log(variable);
// variable이 false면
} else {
console.log('잘못된 값');
}
}
check(null); // 잘못된 값
check(3.14); // 3.14
check(undefined); // 잘못된 값
check(0); // 잘못된 값
check('Good'); // Good
check(''); // 잘못된 값
check(NaN); // 잘못된 값
check(5); // 5
참조
programmers school
: 코딩테스트 광탈 방지 A to Z : JavaScript