ES6学习之路03——对象的解构赋值

2018-03-03  本文已影响0人  现在就是李白

2. 对象的解构赋值

2.1 等号左右两边次序

等号左边的两个变量的次序,与等号右边两个同名属性的次序不一致,但是对取值完全没有影响.

let {one, two} = {one: 1, two: 2};
console.log('one:', one);// one: 1
console.log('two:', two);// two:2

let {three} = {one: 1, two: 2};
console.log('three:', three);// three: undefined
// three变量没有对应的同名属性,导致取不到值,最后等于`undefined`.

2.2. 对象同名属性赋值给等号右边的变量

对象的解构赋值的内部机制,是先找到同名属性,然后再赋给对应的变量.真正被赋值的是后者,而不是前者

let {aaa: bbb} = {aaa: 'AAA', ccc: 'CCC'};
console.log('bbb:', bbb);// bbb: AAA

let {one: n, two: b} = {one: 111, two: 222};
console.log('n:', n);// n: 111
console.log('b:', b);// b: 222

2.3 解构用于嵌套解构的对象

let person = {
    worker: [
        'mark',
        {age: 18}
    ]
};

let {worker: [user, {age}]} = person;
console.log('user:', user);// user: Mark
console.log('age:', age); // age: 18
let person = {
    worker: [
        'mark',
        {age: 18}
    ]
};

let {worker, worker: [user, {age}]} = person;
console.log('worker:', worker);// worker: [ 'mark', { age: 18 } ]
console.log('user:', user);// user: Mark
console.log('age:', age); // age: 18

2.4 嵌套赋值

let obj = {};
let arr = [];

({foo: obj.prop, bar: arr[0]} = {foo: 111, bar: true});
console.log('obj:', obj);// obj: { prop: 111 }
console.log('arr:', arr);// arr: [ true ]

2.5 对象的结构可以指定默认值

{
    let {x = 3} = {};
    console.log('x:', x);// x: 3
}
{
    let {x, y = 5} = {x: 1};
    console.log('x:', x);// x: 1
    console.log('y:', y);// x: 5
}
{
    let {x: y = 3} = {};
    console.log('y:', y);// y: 3
}
{
    let {x: y = 3} = {x: 5};
    console.log('y:', y);// y: 5
}
{
    let {message: msg = 'this is a message'} = {};
    console.log('msg:', msg);// msg: this is a message
}

2.6 对象解构赋值的默认值

默认值生效的条件是,对象的属性值严格等于undefined,如果结构失败,变量的值等于undefined

{
    let {x = 3} = {x: undefined};
    console.log('x:', x);// x: 3
}
{
    let {x = 3} = {x: null};
    console.log('x:', x);// x: null
}

2.7 已声明变量的解构赋值

let x;
// { x } = {x:1};// 这是错误的写法
({x} = {x: 1});
console.log('x:', x);

错误的原因,因为JavaScript引擎会将{x}理解成为一个代码块,从而发生语法错误,只有不将大括号写在行首,避免JavaScript将其解释为代码块,才能解决这个问题.

2.8 古怪的但是没有意义的赋值表达式

({} = [true, false]);
({} = 'abc');
({} = []);

2.9 对象的解构赋值到某一个变量

let {log, sin, cos} = Math;

数组的本质是特殊的对象,因此可以对数组进行对象属性的结垢

let arr = [1, 2, 3];
let {0: first, [arr.length - 1]: last} = arr;
console.log('first:', first);// first: 1
console.log('last:', last);  // last: 3
上一篇下一篇

猜你喜欢

热点阅读