ES6-数组的解构赋值

2018-10-31  本文已影响1人  东邪_黄药师

Destructuring
ES6允许按照一定模式,从数组和对象中提取值,对变量进行赋值,这被称为解构(Destructuring) 。

let [foo, [[bar], base]] = [1, [[2], 3]];
console.log(foo);   //1
console.log(bar);   //2
console.log(base);  //3

let [, , third] = ["first", "second", "third"];
console.log(third); //third

let [one, , three] = ["One", "Two", "Three"];
console.log(one);   //One
console.log(three); //Three

let [head, ...tail] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log(head);  //0
console.log(tail);  //[1, 2, 3, 4, 5, 6, 7, 8, 9]

   var [temp] = [];
console.log(temp);  //undefined
var [first, second] = [100];
console.log(first); //100
console.log(second);//undefined

不完全解构
等号左边的模式,只匹配一部分的等号右边的数组。
位置是严格匹配的

 let [x, y] = [1, 2, 3];
console.log(x); //1
console.log(y); //2

let [a, [b], c] = [1, [2, 3], 4];
console.log(a); //1
console.log(b); //2
console.log(c); //4

指定默认值
注意:ES6内部使用严格相等运算符(===)判断一个位置是否有值。所以,如果一个数组成员不严格等于undefined,默认值是不会生效的。
遍历结构:

 var [temp = "string"] = [];
console.log(temp);  //string

var [temp = "string"] = ["tempString"];
console.log(temp);  //tempString

var [x = "aaa", y] = ["bbb"];
console.log(x); //bbb
console.log(y); //undefined

var [m, n = "aaa"] = ["bbb"];
console.log(m); //bbb
console.log(n); //aaa

var [p, q = "aaa"] = ["bbb", undefined];
console.log(p); //bbb
console.log(q); //aaa

非遍历结构--报错:

var [temp] = 1;         //1[Symbol.iterator] is not a function at eval
var [temp] = false;     //false[Symbol.iterator] is not a function at eval
var [temp] = NaN;       //NaN[Symbol.iterator] is not a function at eval
var [temp] = undefined; //Cannot read property 'Symbol(Symbol.iterator)' of undefined at eval
var [temp] = null;      //Cannot read property 'Symbol(Symbol.iterator)' of null at eval

=========================================================

let和const命令
只要某种数据结构具有Iterator接口,都可以采用数组形式的解构赋值。
Iterator接口:

let [a, b, c] = new Set(["a", "b", "c"]);
console.log(a); //a
console.log(b); //b
console.log(c); //c

function* fibs() {
    let a = 0;
    let b = 1;
    while (true) {
        yield a;
        [a, b] = [b, a + b];
    }
};
var [first, second, third, fourth, fifth, sixth] = fibs();
console.log(sixth); //5
上一篇下一篇

猜你喜欢

热点阅读