ES6新增----解构赋值(其他类型)

参考学习:https://www.cnblogs.com/xiaohuochai/p/7243166.html

1.字符串解构
2.数值和布尔值解构

【字符串解构】
字符串也可以解构赋值。这是因为,字符串被转换成了一个类似数组的对象

const [a, b, c, d, e] = 'hello';
console.log(a);//"h"
console.log(b);//"e"
console.log(c);//"l"
console.log(d);//"l"
console.log(e);//"o"

类似数组的对象都有一个length属性,因此还可以对这个属性解构赋值

const {length} = 'hello';
console.log(length);//5

【数值和布尔值解构】

let {toString:s1} = 123;
console.log(s1 === Number.prototype.toString);//true
let {toString:s2} = true;
console.log(s2 === Boolean.prototype.toString);//true

解构赋值的规则是,只要等号右边的值不是对象或数组,就先将其转为对象。由于undefined和null无法转为对象,所以对它们进行解构赋值,都会报错

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

猜你喜欢

转载自blog.csdn.net/weixin_41989325/article/details/89448013