1. 数组的解构赋值
// 对不需要的值,使用',',将该该值略过。
const [first, , third, ...rest] = [1, 2, 3, 4, 5];
console.log(first) // 1
console.log(third) // 3
console.log(rest) // [4, 5]
const [a, b = 'default'] = []
console.log(a,b) // undefined 'default'
String、Set、Map等所有可遍历对象都能采用解构赋值:
// String
const [A,B,C,D] = 'abcd'
console.log(A,B,C,D) // a b c d
// Set
const[one, two, three, four] = new Set([1, 2, 3, 4])
console.log(one,two,three,four) // a b c d
2.对象的解构赋值
let info = {
name:"David",
age: 24,
weight: 180
};
// 1.同样使用'='赋予默认值 2.变量名可通过解构重新赋予新的名称
let { name, age = 18, weight:height } = info;
console.log(name, age, height) // David 24 180
// 2.仅取部分变量
let { name: nickname, ...rest } = info;
console.log(nickname, rest) // David {age: 24, weight: 180}
// 3.嵌套层级较多的情况,只需对应好顺序及层级即可正确解构
let cellPhone = {
size: {
width: 375,
height: 667
},
package: ['type1', 'type2'],
price: 8888,
};
let { size: {width, height: weight }, package: [, t2 ], price } = cellPhone;
console.log(weight, t2) // 667 "type2"
通过解构赋值改变对象的属性值
const obj = {a: '123', b: '456'};
[obj.a, obj.b] = ['aaa', 'bbb'];
console.log(obj); // {a: "aaa", b: "bbb"}
在for…of中使用
const obj = {a: '123', b: '456'};
for (let [k, v] of Object.entries(obj)) {
console.log(k, v)
}
// a '123'
// b '456'