Deconstruction assignment in ES6
According to the deconstruction of the original value, a part of the original value is quickly obtained (quickly assigned to a variable)
Deconstruction and assignment of arrays
Deconstruction assignment itself is the syntax specification of ES6. It doesn't matter what keywords are used to declare these variables
let ary = [12,23,34];
//Traditional value assignment
// let a = ary[0],
// b = ary[0],
// c = ary[0];
//
// console.log(a, b, c);
//1
let [a,b,c] = [12,23,34];
console.log(a, b, c);//12,23,34
//2
var [a,b,c] = [12,23,34];
console.log(a, b, c);//12,23,34
//3
[a,b,c] =[12,23,34];
console.log(a, b, c);//12,23,34
//This is equivalent to adding global attributes to window, but in strict mode, declaration variable "use strict" such as var/let cannot be used
//4
~function () {
[a,b,c] =[12,23,34];
//This is equivalent to adding global attributes to window, but declaration variables such as var/let cannot be used in strict mode
console.log(a, b, c);//12,23,34
}();
//5
~function () {
[a,b,c] =[12,23,34];
//This is equivalent to adding global attributes to window, but declaration variables such as var/let cannot be used in strict mode
}();
console.log(a, b, c);//12,23,34
//6
~function () {
let [a,b,c] =[12,23,34];
//Private attributes
}();
console.log(a, b, c);//Report errors
The deconstruction and assignment of multi-dimensional array can enable us to get the required results quickly
//let ary = [12,[23,34],[45,56,[67,78]]];
//let A = ary[1][1];
let [,[,A],[,B,[,C]]] = [12,[23,34],[45,56,[67,78]]];
console.log(A, B, C);//34 56 78
If you only want to get some items in the front of the array, the later structure does not need to be completed
let [D] = [12,23,34];
console.log(D);
let [,E] = [12,23,34];
console.log(E); //=>23
In the deconstruction assignment, we can set a default value for an item
let [,,,E] = [12,23,34];
console.log(E); //=>undefined
let [,,,F = 0] = [12,23,34];
console.log(F); //=>0
In the deconstruction assignment, the extension operator of... xxx is supported
let [A,...B] = [12,23,34,45,56];
console.log(A, B);//->12 [ 23, 34, 45, 56 ]
let [...C] =[12,23,34,45,56];
console.log(C);//[12, 23, 34, 45, 56] array clone
let [E,...D,F] = [12,23,34,45,56];
console.log(E, D, F);//Rest element must be last element the extension operator can only appear at the end of a deconstruction assignment
let[G,,,...H] = [12,23,34,45,56];
console.log(G, H); //12 [ 45, 56 ]