解构赋值规则
解构赋值的规则是,只要等号右边的值不是对象或数组,就先将其转为对象。
可结构数据
只要某种数据结构具有 Iterator 接口,都可以采用数组形式的解构赋值
function* fibs() {let a = 0;let b = 1;while (true) {yield a;[a, b] = [b, a + b];}}let [first, second, third, fourth, fifth, sixth] = fibs()
数组默认值
1、=== undefined ,null是空值,不是没值
2、默认值可以是变量
对象的三次解构赋值
const node = {loc: {start: {line: 1,column: 5}}};let { loc, loc: { start }, loc: { start: { line }} } = node;
对象嵌套赋值
let obj = {};let arr = [];({ foo: obj.prop, bar: arr[0] } = { foo: 123, bar: true });obj // {prop:123}arr // [true]
对象的解构赋值可以取到继承的属性
const obj1 = {};const obj2 = { foo: 'bar' };Object.setPrototypeOf(obj1, obj2);const { foo } = obj1;foo // "bar"
对象的默认值
var { message: msg = 'Something went wrong' } = {};
语法
1、赋值表达式,一定要加()
let x;{x} = { x:1 } //err({x} = {x:1})
2、数组本质是特殊的对象,因此可以对数组进行对象属性的解构。
属性名表达式(参见《对象的扩展》)
let arr = [1, 2, 3];let {0 : first, [arr.length - 1] : last} = arr;first // 1last // 3
3、不要使用()
以下三种解构赋值不得使用圆括号
- 变量声明语句 【不可以】
- 赋值语句,而不是声明语句 【可以】
4、Map ```javascript const map = new Map(); map.set(‘first’, ‘hello’); map.set(‘second’, ‘world’);let [(b)] = [3]; // 不正确[(b)] = [3]; // 正确
for (let [key, value] of map) { console.log(key + “ is “ + value); }
// 获取键名 for (let [key] of map) { // … }
// 获取键值 高手 for (let [,value] of map) { // … } ```
