ECMAScript(解构)

2019-04-18  本文已影响0人  fangPeng__

解构

数组解构

对象解构

 let {x, y = 5} = {x: 1};
 x // 1
 y // 5

 let {x: y = 3} = {};
 y // 3

 let {x: y = 3} = {x: 5};
 y // 5

默认值生效的条件是,对象的属性值严格等于undefined。

let {x = 3} = {x: undefined};
x // 3

let {x = 3} = {x: null};
x // null

字符串的解构

const [a, b, c, d, e] = 'hello';
a // "h"
b // "e"
c // "l"
d // "l"
e // "o"


let {length : len} = 'hello';
len // 5

数值和布尔值的解构赋值

解构赋值时,如果等号右边是数值和布尔值,则会先转为对象。

let {toString: s} = 123;
s === Number.prototype.toString // true

let {toString: s} = true;
s === Boolean.prototype.toString // true



let { prop: x } = undefined; // TypeError
let { prop: y } = null; // TypeError

数值和布尔值的包装对象都有toString属性,因此变量s都能取到值。
解构赋值的规则是,只要等号右边的值不是对象或数组,就先将其转为对象。由于undefined和null无法转为对象,所以对它们进行解构赋值,都会报错。

函数参数赋值解构

[[1, 2], [3, 4]].map(([a, b]) => a + b);

赋值默认值同上

圆括号问题

不可使用圆括号

let ([a]) = [1] 或(let [a] = [1]) // 报错
({a: b}) = {a: 1}
{(a): b} = {a: 1}

使用圆括号

{a: (b)} = {a: 1}
({a: b} = {a: 1})
上一篇 下一篇

猜你喜欢

热点阅读