ES6学习之路2----变量的解构赋值

来源:互联网 发布:佳博打印机软件 编辑:程序博客网 时间:2024/05/10 09:01

什么是解构

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

简单的解构赋值

实例:

let [a,b,c] = [1,2,3];等同于:let a = 1,b = 2,c = 3;

数组的解构赋值

数组的元素是按次序排列的,变量的取值由它的位置决定。

1.只要等号两边的模式相同,左边的变量就会被赋予对应的值。
2.如果解构不成功,变量的值就等于undefined。
实例:

let [a,b] = [1];console.log(a);//a = 1console.log(b);//b =  undefined

3.解构赋值允许指定默认值。
实例:

let [x, y = 'b'] = ['a']; console.log(x);// x = 'a'console.log(y);// y = 'b'let [x, y = 'b'] = ['a', undefined]; console.log(x);// x = 'a'console.log(y);// y = 'b'

4.数组的字符串解构
实例:

let [a,b,c] = 'xyz';console.log(a);//'x'console.log(b);//'y'console.log(c);//'z'

5.数组的null和undefined
实例:

let [x, y = 'b',z = 'c'] = ['a', null,undefined]; console.log(x);// x = 'a'console.log(y);// y = nullconsole.log(z);// z = 'c'console.log(null === undefined);//false

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

对象的解构赋值

对象的属性没有次序,变量必须与属性同名,才能取到正确的值。

1.等号两边的属性同名(变量名可以和属性名不同),变量就能取到对应的值。
(1),对象的解构方式一:只要属性同名就能取到值
实例:

let { foo: foo, bar: baz } = { foo: "aaa", bar: "bbb" };console.log(foo);//'aaa'----变量名和属性名相同console.log(baz);//'bbb'----变量名和属性名不同

(2),对象的解构方式二:变量名与属性名必须相同才能取到值
实例:

let { foo, baz } = { foo: "aaa", bar: "bbb" };console.log(foo);//'aaa'----变量名和属性名相同console.log(baz);//undefined----变量名和属性名不同

2.对象的解构赋值,可以很方便地将现有对象的方法,赋值到某个变量。
实例:

let { log, sin, cos } = Math;console.log(log(Math.PI/6));//-0.6470295833786549console.log(sin(Math.PI/6));//0.49999999999999994console.log(cos(Math.PI/6));//0.8660254037844387

3.对象的字符串解构赋值。
实例:

let {length:b} = 'aaa';console.log(b);//3let {a:b} = 'aaa';console.log(b);//undefined

字符串被转换成了一个类似数组的对象。类似数组的对象都有一个length属性,因此还可以对这个属性解构赋值。

4.null,undefined不能解构赋值。
实例:

let {length:b} = null;console.log(b);//Uncaught TypeError: Cannot destructure property `length` of 'undefined' or 'null'.let {length:e} = undefined;console.log(e);//Uncaught TypeError: Cannot destructure property `length` of 'undefined' or 'null'.

由于undefined和null无法转为对象,所以对它们进行解构赋值,都会报错。

圆括号的使用

如果在解构之前,我们就声明了变量,就需要使用圆括号。

1.不使用圆括号
实例:

let a;{a} = {a:'xyz'}console.log(a);//Uncaught SyntaxError: Unexpected token =

2.使用圆括号
实例:

let a;({a} = {a:'xyz'})console.log(a);//'xyz'

总结:

  1. 解构赋值的规则是,只要等号右边的值不是对象,就先将其转为对象。
  2. 如果解构不成功,会赋值undefined。
  3. 由于null,undefined不能转为对象,所以不能进行解构。
  4. null !== undefined,所以有默认赋值时,赋值是undefined时,依然取默认值;如果赋值为null时,取null。
  5. 对已声明变量的解构注意需要使用圆括号。
原创粉丝点击