Destructuring assignment in ES6
According to the deconstruction of the original value, quickly obtain a certain part of the original value (quick assignment to a variable)
数组的解构赋值
Destructuring assignment itself is an ES6 syntax specification, it doesn't matter what keywords are used to declare these variables
let ary = [12,23,34];
//传统的取值赋值操作
// 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
//此处相当于给window加全局属性,但是严格模式下不可以出现非使用var/let等声明变量 "use strict"
//4
~function () {
[a,b,c] =[12,23,34];
//此处相当于给window加全局属性,但是严格模式下不可以出现非使用var/let等声明变量
console.log(a, b, c);//12,23,34
}();
//5
~function () {
[a,b,c] =[12,23,34];
//此处相当于给window加全局属性,但是严格模式下不可以出现非使用var/let等声明变量
}();
console.log(a, b, c);//12,23,34
//6
~function () {
let [a,b,c] =[12,23,34];
//私有属性
}();
console.log(a, b, c);//报错
The destructuring assignment of multidimensional arrays allows us to quickly obtain the required results
//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 the contents of the first few items in the array, the following structures do not need to be completed.
let [D] = [12,23,34];
console.log(D);
let [,E] = [12,23,34];
console.log(E); //=>23
In destructuring 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 destructuring assignment, supported
...xxx
spread operators
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 ] 数组克隆
let [E,...D,F] = [12,23,34,45,56];
console.log(E, D, F);//Rest element must be last element拓展运算符只能出现在解构赋值中的末尾
let[G,,,...H] = [12,23,34,45,56];
console.log(G, H); //12 [ 45, 56 ]