让学习“上瘾”,成为更好的自己!!!
一,字符串的解构赋值
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>字符串的解构赋值</title>
</head>
<body>
<script>
// 字符串也可以解构赋值 --> 此时的字符串被转换成一个类似数组的对象
const [a, b, c, d] = 'hello';
console.log(a);
console.log(b);
console.log(c);
// 类似于数组的对象都有一个length属性
let {length: len} = 'hello';
console.log(len); // 5
</script>
</body>
</html>
二,数值和布尔值的解构赋值
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>数值和布尔值的解构赋值</title>
</head>
<body>
<script>
// 结构赋值时,如果等号右边是“数值”和“布尔值”,则会先装换为对象
// let {toString: s} = 1231;
// console.log(s === Number.prototype.toString); // true
let {toString: s} = true;
console.log(s === Boolean.prototype.toString); // true
var aa = new Number(33);
console.dir(aa);
// 上面的代码中,数值和布尔值的包装对象都有toString属性,因此变量s可以取到值
// 【解构赋值的规则】
// 只要等号右边的值不是对象或者数组,就先将其转换为对象,undefined and null无法转为对象,对他们进行解构赋值都会报错
let {prop1: x} = undefined;
let {prop2: y} = null;
// Cannot destructure property `prop1` of 'undefined' or 'null'.
</script>
</body>
</html>