一、数组的解构赋值的规律
- 只要等号两边的模式相同,左边的变量就会被赋予对应的值
二、数组的解构赋值的例子讲解
1)简单的示例(完整的解构赋值)
let [ a, b, c] = [ 1 , 2 , 3 ] ; console. log ( "a=" + a) ; console. log ( "b=" + b) ; console. log ( "c=" + c) ;
效果
2)简单的示例(部分的解构赋值)
let [ , , c] = [ 1 , 2 , 3 ] ; console. log ( "c=" + c) ;
效果 示例二(前者部分赋值)
let [ a, b] = [ 1 , 2 , 3 ] ; console. log ( "a=" + a) ; console. log ( "b=" + b) ;
效果
3)过度解构赋值
如果解构不成功,一般变量的值就等于undefined
let [ a, b, c, d] = [ 1 , 2 , 3 ] ; console. log ( "a=" + a) ; console. log ( "b=" + b) ; console. log ( "c=" + c) ; console. log ( "d=" + d) ;
效果
4)较为复杂的解构赋值
let [ a, [ [ b] , c] ] = [ 1 , [ [ 2 ] , 3 ] ] ; console. log ( "a=" + a) ; console. log ( "b=" + b) ; console. log ( "c=" + c) ;
效果
5)剩余运算符
let [ first, ... other] = [ 1 , 2 , 3 , 4 ] ; console. log ( "first=" + first) ; console. log ( "other=" + other) ;
效果
6)默认值
- 解构赋值允许指定默认值
let [ a, b = 1 ] = [ 1 , 2 , 3 ] ; console. log ( "a=" + a + ",b=" + b) ; let [ a1, b1 = 1 ] = [ 1 ] ; console. log ( "a1=" + a1 + ",b1=" + b1) ; let [ a2 = 1 ] = [ null ] ; console. log ( "a2=" + a2) ; let [ a3 = 1 ] = [ undefined ] ; console. log ( "a3=" + a3) ;
效果 问题
- 大家可能有个疑惑
- 问题:为什么语句let [ a3 = 1 ] = [ undefined] ; 中a3对应的值为undefined,为什么运行结果a3= 1 ?
- 答案:ES6 内部使用严格相等运算符(== = ),判断一个位置是否有值,当一个数组成员严格等于undefined,默认值就会生效
- 默认值可以引用解构赋值的其他变量,但该变量必须已经声明
let [ x = 1 , y = x] = [ ] ;
let [ x = 1 , y = x] = [ 2 ] ;
let [ x = 1 , y = x] = [ 1 , 2 ] ;
let [ x = y, y = 1 ] = [ ] ;