Appearance
基本数据类型的解构
本节目标:理解“基本数据类型的解构”的核心思路,并能把它用于实际开发或面试表达。 解构赋值的规则是,只要等号右边的值不是对象或数组,就先将其转为对象。
一、由于undefined和null无法转为对象,所以对它们进行解构赋值,都会报错。
let { prop: x } = undefined; // TypeErrorlet { prop: y } = null; // TypeError二、解构赋值时,如果等号右边是数值和布尔值,则会先转为对象。
let {toString: s} = 123;s === Number.prototype.toString // true
let {toString: s} = true;s === Boolean.prototype.toString // true
上面代码中,数值和布尔值的包装对象都有toString属性,因此变量s都能取到值。三、字符串解构赋值时,会被转换成了一个类似数组的对象。
const [a, b, c, d, e] = 'hello';a // "h"b // "e"c // "l"d // "l"e // "o"
类似数组的对象都有一个length属性,因此还可以对这个属性解构赋值。
let {length : len} = 'hello';len // 5