ES6-Deconstruction and Assignment of Objects

ES6-Deconstruction and Assignment of Objects

Like arrays, objects can also be destructured

let {name, age} = {name: 'jisoo',  age:25};
console.log(name);//'jisoo'
console.log(age);//25

However, there is a difference between the destructuring assignment of an object and the destructuring assignment of an array. The elements of the array are arranged in order, and the value of the variable is determined by its position, and the attributes of the object have no order. The variable must have the same name as the attribute. To the correct value

let {job, salary}={salay: 20000, job: 'doctor'};
console.log(salary);//20000
consol.log(job);//'doctor'

As with arrays, undefined will be returned if the value is not available

let {gender}={sex: 'female', level: 'boss'};
console.log(gender);//undefined

Object deconstruction assignment is a shorthand for the following code let {foo: foo , bar: bar} = {foo: 'aaa', bar: 'bbb'}, that is, the internal mechanism of object deconstruction assignment is to find the attribute with the same name first, and then assign it to the corresponding variable. The latter is actually assigned instead of the former, as shown in the following code Show:

let obj = {first: 'hello', last: 'world'};
let {first: f, last: l}=obj;
console.log(f);//first
console.log(l);//last
console.log(first);//Error(first is not defined)

Like arrays, destructuring can also be used for objects with nested structures

        let obj1 = {
            p: ['hello', {
                y: 'world'
            }]
        };
        let {
            p: [x, {
                y
            }]
        } = obj1;
        console.log(x); //'hello'
        console.log(y); //'world'

The deconstruction of the object can also use the default value. The condition for the default value to take effect is that the property of the object is strictly equal to undefined

        var {
            x3 = 3
        } = {
            x: undefined
        };
        console.log(x3); //3
        var {
            x4 = 3
        } = {
            x4: null
        }
        console.log(x4); //null

Since the array is a special object, it can deconstruct the object property of the array

        let arr = [1, 2, 3];
        let {
            0: first1,//0号索引
            [arr.length - 1]: last1//2号索引
        } = arr;
        console.log(first1); //1
        console.log(last1); //3

Guess you like

Origin blog.csdn.net/Angela_Connie/article/details/110998252