ES6(二)变量的结构赋值

101 阅读1分钟

ES6允许按照一定模式从数组和对象中提取值,对变量进行赋值,这被称为解构赋值。

数组的解构赋值

let [z,q,s,l,w] = ['赵','钱','孙','李','吴'];
console.log(l);    //李

允许设置默认值

let [x, y = 'b'] = ['a', undefined]; // x='a', y='b'
console.log(x, y);

对象的解构赋值

不受顺序影响,也允许设置默认值

 let obj = {
     name: 'xx',
     age: 18,
     habbit: ['吃饭', '睡觉', '听歌'],
     history: [
         { name: 'qq' },
         { name: 'ww' },
         { name: 'ee' }
     ]
 };
//对象解构赋值不受顺序影响
let { age: a, name, habbit: [cf, sj, tg], history: [{ name: name1 }, { name: name2 }, { name: name3 }] } = obj;
console.log(name);
console.log(cf);
console.log(name3);
console.log(a);

注意:频繁使用对象方法、数组元素,就可以使用解构赋值形式

字符串的解构赋值

字符串被转换成了一个类似数组的对象,有length属性

const [a, b, c, d, e] = 'hello'
console.log(a); //'h'

let { length } = 'hello'
console.log(length);  //5

函数参数的解构赋值

function add({ x = 0, y = 0 } = {}) {
    return [x, y]
}
console.log(add({ x: 1, y: 2 }));   //[1,2]
console.log(add({ x: 1 }));   //[1,0]