Function: ES6 allows to extract values from arrays and objects in a certain way, and to assign values to variables, which is called destructuring assignment.
Array destructuring:
let [a, b, c] = [1, 2, 3];
console.log(a)
console.log(b)
console.log(c)
If the destructuring is unsuccessful, the value of the variable is undefined.
let [foo] = []; //Cannot redeclare block-scoped variable 'foo'
let [bar, foo] = [1]; //Cannot redeclare block-scoped variable 'foo'.
Replenish:
// 定向取法
let arr1 = [1, 2, 3];
let [,,d] = arr1;
console.log(d); //3
// 嵌套写法
let arr = [1, [2, 3], 4];
let [a, [b, ], c] = arr;
console.log(b); //2
Object destructuring:
let person = { name: 'zhangsan', age: 20 };
let { name, age } = person;
console.log(name); // 'zhangsan'
console.log(age); // 20
let person = { name: 'zhangsan', age: 20 };
let {name: myName, age: myAge} = person; // myName myAge 属于别名
console.log(myName); // 'zhangsan'
console.log(myAge); // 20
Replenish:
let code = "AAAA"
let res = {
code: 200,
data: {
list: ["aaa", "bbb", "ccc"]
}
}
// 重命名写法
let {code:co} = res;
console.log(co); // 200
// 数组嵌套写法
let {data:{list:[x, y, z]}} = res;
console.log(x, y, z); // aaa bbb ccc
Practical application:
Destructuring the return parameter
function getData() {
let res = {
code: 200,
data: {
list: ["aaa", "bbb", "ccc"]
}
}
test(res)
}
function test({code, data:{list}}) {
console.log(code, list);
}
getData(); // 200 ['aaa', 'bbb', 'ccc']
Note: In the destructuring syntax, the left side of the colon is used to match the value, and the right side of the colon is the real variable