배열이나 객체의 속성을 해체해 그 값을 개별 변수에 담는 것
arr[0], arr[1]
처럼 접근하는 것이 아닌 각각의 배열 요소를 변수의 이름으로 접근하기 위해서 사용
const arr5 = ['tomato', 'kiwi', 'banana'];
const [tomato, kiwi, banana] = arr5;
console.log(tomato);
let tomato = arr5[0];
let kiwi = arr5[1];
let banana = arr5[2]
const[변수] = 배열
let lists = ['apple', 'grape']
[item1, item2, item3 = 'peach'] = lists;
console.log("item1 : ", item1);
console.log("item2 : ", item2);
console.log("item3 : ", item3);
객체의 속성값을 key로 접근하는 것이 아닌 변수로 접근하기 위해서 사용
const obj = {
title: '제목'
content: '내용'
num: 0;
};
const{title, num, content} = obj
console.log(content); //내용
const title = obj.title;
const num = obj.num;
const content = obj.content;
배열의 구조분해 할당과 달리 변수 선언 순서에 따라서 값이 할당되는 것이 아닌 key의 이름에 따라서 변수에 값이 할당됨
const{변수} = 객체
let obj = {
key1: 'one',
key2: 'two'
};
let {key1: newKey1, key2, key3 = 'three'} = obj;
console.log("key1 : ", key1);
console.log("newKey1 : ", newKey1);
console.log("key2 : ", key2);
console.log("key3 : ", key3);
const a = [1, 2, 3];
const b = [4, 5];
const spread = [...a, ...b];
console.log(spread);
const c = [..."Hello"];
console.log(c);
[1, 2, 3, 4, 5]
...[1, 2, 3, 4, 5]
const arr1 = [1, 2, 3, 4, 5];
const arr2 = ["a", "b", "c"];
const arr3 = [...arr1, ...arr2];
const values = [10, 20, 30];
function get(a, ...rest) {
console.log(rest); //결과는 [20, 30]
}
get(...values);
객체를 생성하기 위한 템플릿
ex) 객체 : 고양이 그 자체
속성 : 이름 - 나비, 나이 - 1살
메소드 : mew() - 울다, eat() - 먹는다
class Car {
constructor(name, age){
//속성
this.name=name;
this.age=age;
}
//메소드
mew(){
console.log("야옹");
}
eat() {
console.log("먹이를 먹습니다.");
}
}
let cat1 = new Cat('나비', 1);
let cat2 = new Cat('냥이', 2);
cat1.mew();
cat1.eat();
cat2.mew();