
第3章 变量的解构赋值
3.1 数组的解构赋值
3.1.1 基本用法
ES6 允许按照一定模式从数组和对象中提取值,然后对变量进行赋值,这被称为解构(Destructuring)。
以前,为变量赋值只能直接指定值。

ES6允许写成下面这样。

上面的代码表示,可以从数组中提取值,按照对应位置对变量赋值。
本质上,这种写法属于“模式匹配”,只要等号两边的模式相同,左边的变量就会被赋予对应的值。下面是一些使用嵌套数组进行解构的例子。


如果解构不成功,变量的值就等于undefined。

以上两种情况都属于解构不成功,foo的值都会等于undefined。
另一种情况是不完全解构,即等号左边的模式只匹配一部分的等号右边的数组。这种情况下,解构依然可以成功。

上面两个例子都属于不完全解构,但是可以成功。
如果等号的右边不是数组(或者严格来说不是可遍历的结构,参见第 15 章),那么将会报错。


上面的语句都会报错,因为等号右边的值或是转为对象以后不具备Iterator接口(前五个表达式),或是本身就不具备Iterator接口(最后一个表达式)。
对于Set结构,也可以使用数组的解构赋值。

事实上,只要某种数据结构具有Iterator接口,都可以采用数组形式的解构赋值。

上面的代码中,fibs是一个Generator函数(参见第16章),原生具有Iterator接口。解构赋值会依次从这个接口中获取值。
3.1.2 默认值
解构赋值允许指定默认值。

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

上面的代码中,如果一个数组成员是 null,默认值就不会生效,因为 null 不严格等于undefined。
如果默认值是一个表达式,那么这个表达式是惰性求值的,即只有在用到时才会求值。

上面的代码中,因为x能取到值,所以函数f根本不会执行。上面的代码其实等价于下面的代码。

默认值可以引用解构赋值的其他变量,但该变量必须已经声明。

上面最后一个表达式之所以会报错,是因为x用到默认值y时,y还没有声明。