一、字符串解构赋值
- 基本用法:
const [a, b, c, d, e] = 'hello';
a // "h"
b // "e"
c // "l"
d // "l"
e // "o"
const [a,b,c] = '12';
console.log(a,b,c) // 1 2 undefined
如果匹配不到,值为undefined。
- 字符串属性的解构赋值(要写字符串有的属性)
const {length:len} = 'hello' //length属性
console.log(len); //5
二、数值和布尔值的解构赋值
解构赋值时,如果等号右边是数值和布尔值,则会先转为对象。
let {toString: s} = 123;
console.log(s === Number.prototype.toString) //true
let {toString: s} = true;
console.log(s === Boolean.prototype.toString) //true
上面代码中,数值和布尔值的包装对象都有toString属性,因此变量s都能取到值。
解构赋值的规则是,只要等号右边的值不是对象,就先将其转为对象。由于undefined和null无法转为对象,所以对它们进行解构赋值,都会报错。
let { prop: x } = undefined; // TypeError
let { prop: y } = null; // TypeError






网友评论