ES6 解构

1.解构赋值

以前:

let a = 1
let b = 2
let c = 3

现在支持:

let [a, b, c] = [1, 2, 3]

原理

模式匹配,只要等号两边的模式相同,左边的变量就会被赋予对应的值。

嵌套数组的解构例子:
let [a, [[b], c]] = [1, [[2], 3]]

对应的是:a = 1, b = 2, C = 3

let [ , , c] = [1,2,3]

对应的是:C = 3

let [ a, , c] = [1,2,3]

对应的是:a = 1, C = 3

let [head, ...tail] = [1,2,3,4,5]

对应的是:head = 1, tail = [ 2, 3, 4, 5 ]

let [a, b, ...z] = [1]

对应的是:a = 1, b = undefined, C = []

let [a] = []

对应的是:a = undefined

没有解构成功的值将会等于 undefined。

不完全解构

let [a,b] = [1,2,3]
let [a,[b], c] = [1,[2,3],4]