구조분해 할당

이재영·2023년 3월 27일
0

HTML CSS JS

목록 보기
9/22
post-thumbnail

ES5 문법에서는 배열의 값을 호출해 변수에 담거나 사용할 때

let a;
let b;
let arr=[1,2,3,4];

a=arr[1];
b=arr[3];
console.log(a,b);
2 4 가 출력된다.

ES6에서 구조분해할당을 이용해 배열의 값을 호출해 변수에 담거나 사용할 때

let arr=[1,2,3,4];
let [a,b,c,d]=arr;
console.log(a,b,c,d);
1 2 3 4 출력된다.
let [e,f]=[1,2,3];
console.log(e,f);
1 2 출력된다. 넘쳐도 상관없다. 반대로 없으면 undefined가 출력된다.
let [a,b,c=1] =[2,3];
console.log(a,b,c);
2 3 1 출력된다. 디폴트 값을 1로 주었고, 나머지는 다른 값으로 덮어씌워지지만 c는 값이 없기때문에 디폴트 값인 1로 출력된다.

ES5의 객체 값 변수 할당할 때

let name = {firstName :"lee", lastName :"kim"};

let name1 = name.firstName;
let name2 = name.lastName;
console.log(name1,name2);
lee kim 출력된다.

ES6 객체의 각 키를 뽑아서 변수에 할당.

let {firstName,lastName} = name;
console.log(firstName,lastName); // lee kim
console.log(lastName,firstName); // kim lee

let name4 = {firstName = "lee", lastName} = {firstName : "lee2" , lastName : "kim"};
console.log(firstName,lastName);
lee2 kim 출력된다.

문자열 구조분해할당

let str = "abcdefg"
let {length} = str;
console.log(length); // 7 출력된다.

객체안에 필요한 값만 호출할 때
ex > id 값만 뽑아온다.

let list1 =[{id :1, content : "abcdefg", isActive : true},
            {id :2, content : "abcdefg", isActive : true},
            {id :3, content : "abcdefg", isActive : true}, 
            {id :4, content : "abcdefg", isActive : true}]

list1.forEach(function(i){
    let{id}=i;
    console.log(id);
})
1 2 3 4 출력된다.

let user = {
    name : "lee",
    address : {
        city : "seoul"
    }
}
구조분해할당으로 city 값 할당.
let {address:{city}} =user;

스프레드 연산자

  • 연산자 구문은 ...으로 사용한다.
  • 본 객체를 변경하지않고 새로운 객체를 만들어준다.
  • let temp1 = [1,2,3];
    let temp2 = [4,5,6,7];
    
    let temp3 = [...temp,...temp2];
    console.log(temp3);
    출력결과 [1,2,3,4,5,6,7] 이라는 새로운 객체가 생성된다.
    let obj = {
        aa:1,
        b:2
    }
    let obj2 = {
        a:2,
        b:3,
        c:1
    }
    let obj4 = {
        a:3,
        b:4,
        c:4
    }
    
    let obj3 = {...obj,...obj2,...obj4};
    
    console.log(obj3);
    a:3 aa:1 b:4 c:4 출력된다. 키값이 동일한 경우엔 마지막 값으로 할당된다.
    profile
    한걸음씩

    0개의 댓글