ES6 -- destructuring
程序员文章站
2024-02-14 17:19:46
...
解构(结构化赋值)
解构一般用于复杂数据里面需要分开操作的时候
- 解构过程中,具备赋值和变量声明两个功能
- 目的在于吧等号左右长得相似的两个东西内部的值取出来
- 对象数组都可以参与解构
let obj = {name: ‘yq’, age: 20};
let {name, age} = obj; 或 let name, age; ({name, age}, obj);
// 解构对象
let obj = {
name: 'yq',
age: 20
}
let {name, age} = obj; // 将对象里面的值全部赋给左侧的变量
console.log(name, age); // yq, 20
let {name: myName, age: myAge} = obj;
console.log(myName, myAge); // yq, 20
let obj1 = {
name: 'ymy',
age: 21,
ySex: 'female'
}
let {name: mName, age: mAge, mSex = 'male'} = obj; // 默认赋值
let {name: yName, age: yAge, ySex = 'male'} = obj1;
console.log(mName, mAge, mSex); // yq, 20, male
console.log(yName, yAge, ySex); // ymy, 21, female
// 解构数组
let arr = [1, 2, 3];
let {0: x, 1: y, 2: z} = arr;
let [a, b, c] = arr;
let {length} = arr;
console.log(x, y, z); // 1 2 3
console.log(a, b, c); // 1 2 3
console.log(length); // 3