2022.04.18 - javascript 기초 (배열, 구조분해할당, 전개 연산자)
1. 배열
2. 구조 분해 할당 (Destructuring assignment)
비구조화 할당이라고도 한다.
const user = {
name: "myomyo",
age: 94,
email: "myo123@mail.com",
address: "korea",
};
const { name, age, email, address } = user;
console.log(`사용자의 이름은 ${name}입니다. `);
=> 사용자의 이름은 myomyo입니다.
console.log(`${name}의 나이는 ${age}년생 입니다. `);
=> myomyo의 나이는 94년생입니다.
console.log(`${name}의 이메일 주소는 ${email} 입니다. `);
=> myomyo의 이메일 주소는 myo123@mail.com 입니다.
console.log(address);
=> address 값을 추가해주지 않을 경우 undefined 가 출력됨
=> korea
const fruits = ["사과", "바나나", "딸기"];
const [, , c] = fruits;
console.log(c);
==> 세번째에 해당되는 '딸기'가 출력됨
3. 전개 연산자 (Spread)
const fruits = ["사과", "딸기", "배"];
console.log(fruits);
console.log(...fruits);
// 문자 데이터 형태로 쉼표로 구분된 각각의 아이템으로 배열데이터가 전개되어 나뉘어진다. (...) => 전개하는 연산자
function toObject(a, b, c) {
return {
a: a,
b: b,
c: c,
};
}
console.log(toObject(...fruits));
// a:'사과 , b:'딸기' , c:'배'
+ 이때, fruits에 오렌지를 추가하고 전개연산자를 사용하여 매개변수에 a,b 다음에 ...c 를 사용하면
const fruits = ["사과", "딸기", "배", "오렌지"];
function toObject(a, b, ...c) {
return {
a: a,
b: b,
c: c,
};
}
console.log(toObject(...fruits));
==> a:'사과', b:'딸기', c:Array(2)
a와 b는 알맞게 들어가고 나머지 데이터들은 모두 c로 들어가게된다.
이것을 나머지 매개변수(rest parameter) 라고한다.
+ 함수내부에서 속성의 이름과 변수의 이름이 같을경우 하나만 남겨도 출력된 값은 같다.
function toObject(a, b, ...c) {
return {a, b, c}
}
console.log(toObject(...fruits));
+ 해당 함수 화살표함수로 짧게 정리하기
const toObject = (a, b, ...c) => ({a, b, c});
console.log(toObject(...fruits));