DBILITY

독거 가능성 100% 노후에 라면값이라도 하게 센스를 발휘합시다!😅
Please click on the ad so that I can pay for ramen in my old age!
点击一下广告,让老后吃个泡面钱吧!
老後にラーメン代だけでもするように広告を一回クリックしてください。

javascript es6 destructuring assignment ( 구조분해할당 ) 본문

front-end & ui/javascript

javascript es6 destructuring assignment ( 구조분해할당 )

DBILITY 2021. 12. 22. 08:55
반응형

Array나 Object의 자료를 꺼내 변수에 할당하는 경우는 많다. 손쉽게 할 수 있는 destructuring문법이 추가되었다.

    var [a, b, c, d = 0, e] = [1, 2, 3];
    console.log(a);
    console.log(b);
    console.log(c);
    console.log(d);
    console.log(e);

    var obj = {name: '이도', born: 1397, age: new Date().getFullYear() - 1397};
    console.log(obj);

    var {name} = obj;
    console.log(name);

    var {name, born, age = 100} = obj;
    console.log(name, born, age);

    var {name, born, age} = obj;
    console.log(name, born, age);

    var {name, born, age1} = obj;
    console.log(name, born, age1);

    //콜론은 '분해하려는 객체의 프로퍼티: 목표 변수’와 같은 형태
    var {name: callsign, born, age: age1} = obj;
    console.log(callsign, born, age1);

    var obj2 = {name: callsign, year: born, age1}
    console.log(obj2);

    fn({name, born, age});

    function fn({name,born}) {
        console.log(name);
        console.log(born);
    }

    fn2([name, born, age]);

    function fn2([name,born,age]) {
        console.log(name);
        console.log(born);
        console.log(age);
    }

d의 경우 default값을 설정한 것. e의 경우 할당을 안했으니 undefined가 출력된다.

Object의 경우 mustache를 사용하는데, default값은 object에 match 되는 key가 없을 때만 된다.

object의 key와 동일한 명을 사용해야 하나 variable name : new name형태로는 새로운 명칭을 줄 수 있다.

함수 파라미터로도 줄 수 있다. 세상 좋아졌네.

결과

반응형

'front-end & ui > javascript' 카테고리의 다른 글

javascript es6 promise  (0) 2021.12.22
javascript es6 import/export for variable,function,class  (0) 2021.12.22
javascript es5 inheritance ( 상속 )  (0) 2021.10.29
javascript constructor function  (0) 2021.10.29
javascript es6 class  (0) 2021.10.28
Comments