ES 6 系列二

变量的解构赋值

es 6 允许按照一定的模式,从数组和对象中提取值,然后对变量进行赋值,这被称之为解构;

一.数组的解构赋值

  最基本写法:

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

  更多的写法:

let [foo, [[bar], baz]] = [1, [[2], 3]];
foo // 1
bar // 2
baz // 3

let [ , , third] = ["foo", "bar", "baz"];
third // "baz"

let [x, , y] = [1, 2, 3];
x // 1
y // 3

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

let [x, y, ...z] = ['a'];
x // "a"
y // undefined
z // []

  

猜你喜欢

转载自www.cnblogs.com/cc-freiheit/p/9140406.html