Deconstruction Assignment of arrays
ES6 allows you to extract values from arrays and objects in a certain pattern, assigning values to variables, which is called deconstruction (destructuring).
Previously, assigning a value to a variable could only be specified directly.
let a = 1;let b = 2;let c = 3;
ES6 allowed to be written as follows.
let [a,b,c] = [1,2,3];console.log(a); // 1console.log(b); // 2console.log(c); // 3
The following will also be parsed
let [foo, [[bar], baz]] = [1, [[2], 3]];foo // 1bar // 2baz // 3let [ , , third] = ["foo", "bar", "baz"];third // "baz"let [x, , y] = [1, 2, 3];x // 1y // 3
If the deconstruction is unsuccessful, the value of the variable is equal to undefined.
If the right side of the equal sign is not an array (or, strictly speaking, not a ergodic structure), an error will be reported.
// 报错let [foo] = 1;let [foo] = false;let [foo] = NaN;let [foo] = undefined;let [foo] = null;let [foo] = {};
For a SET structure, you can also use the destructor of an array to assign a value.
let [x, y, z] = new Set(['a', 'b', 'c']);console.log(x) // "a"console.log(y) // "b"console.log(z) // "c"
The deconstruction assignment allows you to specify a default value.
var [foo = true] = [];console.log(foo) // truevar [x, y = 'b'] = ['a']; // x='a', y='b'console.log(x);console.log(y);var [x, y = 'b'] = ['a', undefined]; // x='a', y='b'console.log(x);console.log(y);var [x, y = 'b'] = ['a', 'c']; // x='a', y='c'console.log(x);console.log(y);
Note that the ES6 internally uses the strict equality operator (= = =) To determine whether a position has a value. Therefore, the default value will only take effect if an array member is strictly equal to undefined.
var [x = 1] = [undefined];console.log(x) // 1var [x = 1] = [null];console.log(x) // null
In the above code, if an array member is NULL, the default value does not take effect because NULL is not strictly equal to undefined.
let [x = 1, y = x] = []; // x=1; y=1let [x = 1, y = x] = [2]; // x=2; y=2let [x = 1, y = x] = [1, 2]; // x=1; y=2let [x = y, y = 1] = []; // ReferenceError: y is not defined
Deconstruction assignment of ES6 array