ES6-Destructuring and Assignment of Arrays
- The definition of destructuring
ES6 allows extracting values from arrays and objects according to certain patterns, and then assigning values to variables.
In the past, assigning values to variables could only be specified directly, for example:
let a=1;
let b=2;
let c=3;
Since ES6 introduced destructuring assignment, variables can be defined as follows:
let [d, e, f] = [4, 5, 6];
console.log(d, e, f); //4 5 6
console.log([d, e, f]); //[4,5,6]
The above code extracts values from the array and assigns values to the variables according to the corresponding positions. In essence, this type of writing belongs to pattern matching. As long as the patterns on both sides of the equal sign are the same, the variable on the left will be assigned the corresponding value.
- Array destructuring assignment can be nested, if the destructuring is unsuccessful, the value of the variable will return undefined
let [x, [y, z]] = [1, [2, 3]];
console.log(x, y, z); //1 2 3
let [, , third] = ['a', 'b', 'c'];
console.log(third); //'c'
let [head, ...tail] = [1, 2, 3, 4, 5];
console.log(head, tail); //1 [2,3,4,5]
let [m, n, ...o] = ['a'];
console.log(m); //'a'
console.log(n); //undefined
console.log(o); //[]
- Incomplete deconstruction
The pattern on the left side of the equal sign only matches a part of the array on the right side of the equal sign. In this case, the deconstruction can still be successful
let [g, h] = [1, 2, 3];
console.log(g); //1
console.log(h); //2
console.log([g, h]); //[1,2]
- Destructuring assignment allows you to specify default values
let [foo = true] = [];
console.log(foo); //true
let [x1, y1 = 'b'] = ['a', undefined];
console.log(x1); //'a'
console.log(y1); //'b'
- ES6 internally uses the strict equality operator'===' to determine whether a position has a value. Therefore, if an array member is not strictly equal to undefined, the default value will not take effect
let [x2 = 1] = [undefined];
console.log(x2); //1
let [x3 = 1] = [null];
console.log(x3); //null
- If the default value is an expression, then the expression is evaluated lazily, that is, it will only be evaluated when it is used
function fn() {
console.log('aaa');
}
let [x4 = fn()] = [1];
console.log(x4); //1(x4能取到值,所以函数fn()根本不会执行)
/* 以上代码等价于 */
// let x4;
// if (([1][0]) === undefined) {
// x4 = fn();
// } else {
// x4 = [1][0];
// }
// console.log(x4);//1