注意点:
1、等号左右两边结构必须一样
let [a,b] = {a: 1, b: 2} //TypeError: {(intermediate value)(intermediate value)} is not iterable
2、右边结构语法必须正确。{1, 2}既不是对象,也不是数组,语法不正确
let {a,b} = {1, 2} // SyntaxError: Unexpected token ,
3、声明与赋值不能分开
let [a, b] //声明 [a, b] = [1, 2] //赋值 // SyntaxError: Missing initializer in destructuring declaration(解构声明缺乏初始化)
可以这样先声明后赋值
let a, b
[a, b] = [1, 2]
数组的解构赋值
剩余模式
let [a, b, ...rest] = [10, 20, 30, 40, 50] console.log(a) //10 console.log(b) //20 console.log(rest) //[30,40,50]
前后数量不同
变量多时,值为undefined
let [a, b] = [1] console.log(a); // 1 console.log(b); // undefined
变量少时,忽略后面的值
let [a, b] = [1, 2, 3, 4, 5] console.log(a); // 1 console.log(b); // 2 //后面的值忽略
设置默认值
let [a = 2, b = 7] = [1] console.log(a) //1 console.log(b) //7
交换变量
let a = 3, b = 1 //这里的分号不加会报错,ReferenceError: Cannot access 'b' before initialization [a, b] = [b, a] console.log(a) //1 console.log(b) //3
对象的解构赋值
基本赋值
let { a, b } = { a: 1, b: 2 } console.log(a) //1 console.log(b) //2
先声明后赋值
let a, b;
({ a, b } = { a: 1, b: 2 })
这里的(...)必须加
给新的变量名赋值
let { a: c, b: d } = { a: 1, b: 2 } console.log(c) //1 console.log(d) //2
默认值
与数组解构类似
let { a = 10, b = 20 } = { a: 1 } console.log(a) //1 console.log(b) //20
给新的变量命名并提供默认值
let { a: c = 10, b: d = 20 } = { a: 1 } console.log(c) //1 console.log(d) //20
剩余模式
let { a, b, ...rest } = { a: 10, b: 20, c: 30, d: 40 } console.log(rest) //{c: 30, d: 40}
解构对象会查找原型链
var obj = { a: 1 }; Object.prototype.b = 2; // 或者 // obj.__proto__.b = 2 const { a, b } = obj; console.log(a) //1 console.log(b) //2