ES6学习——新的语法:数组解构(Array Destructuring)

时间:2022-06-08 18:26:52

上一篇文章讲了Object的解构,这篇讲一下Array的解构,概念大同小异,只是写法会有一些不同,先看个简单的例子:

let [x, y] = ['a', 'b','c']; // x = 'a'; y = 'b'

跟对象解构一样,先探讨一下赋值表达式的右侧应具备什么条件才能进行解构赋值,规范的12.14.5.2有这样的描述:

ArrayAssignmentPattern : [ ] 

1. Let iterator be GetIterator(value). 

2. ReturnIfAbrupt(iterator). 

3. Return IteratorClose(iterator, NormalCompletion(empty)). 

从上面的描述看,右侧应该是个iterator对象,具体什么样的对象才能算是iterator,后面章节会详细讲,这里就不仔细说了,先记住就好了。

let x;
[x] = {}; // TypeError, empty objects are not iterable
[x] = undefined; // TypeError, not iterable
[x] = null; // TypeError, not iterable
上面的例子说明了对象,undefined,null不是iterator对象。


下面看一些数组解构的特性:

let [x] = []; // x = undefined

var o = {},a =[];
[o.a, o.b, o.c,a[0]] = [1,2,3,4];
//o:{ a: 1, b: 2, c: 3 },a:[4]

let [x,...y] = 'abc'; // x='a'; y=['b', 'c'],rest操作符

var o = [1,2,3],
a, b, c, p;
p = [,,c] = [a,b] = o;//解构连续赋值
trace( a + " " + b + " " +c ); // 1 2 3
trace(p === o); // true

var a1 = [ 1, [2, 3, 4,7,8], 5 ];//嵌套解构+rest操作符
var [ a, [ b, c,...d], e ] = a1;
//a=1,b=2,c=3,d=[4,7,8],e=5

下面看一下如何用数组解构交换两个变量的值:

var x = 10, y = 20;
[ y, x ] = [ x, y ];//如此的优雅

//如果还借助临时变量,还可以用异或操作符,当然不好理解
x^=y;
y^=x;
x^=y;

在对象解构的时候有默认值的使用,同样数组解构也可以有默认值:

let [x=3, y] = []; // x = 3; y = undefined

let [x=1] = [undefined]; // x = 1

function log(x) { trace(x+"\n"); return 'YES' }
let [a=log('hello')] = [1];//a = 1
let [a=log('hello')] = [0];//a = 'YES',注意这里Kinoma和ES6规范的区别,在Firefox43下,a=0

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

let [x=y, y=3] = []; // ReferenceError,从左到右evaluate

let [{ prop: x } = {}] = [];//x=undefined
let [{ prop: x } = {}] = [1];//x=undefined
let [{ prop: x } = { prop: 123 }] = [];//x=123
let [{ prop: x } = { prop: 123 }] = [{prop:1}];//x=1

 
介绍完了上面这些特性,下面看个实际使用中的例子: 

let [all, year, month, day] =/^(\d\d\d\d)-(\d\d)-(\d\d)$/.exec('2015-12-31');
//all="2015-12-31",year="2015",month="12",day="31"

let [, , , day] =/^(\d\d\d\d)-(\d\d)-(\d\d)$/.exec("test") || [];
//day=undefined,如果不写||[],将会报错,因为exec返回null,而null是不能进行解构的

*以上全部代码在Kinoma Studio中通过测试