Skip to content

其它数据类型解构赋值

字符串的解构赋值

字符串的解构赋值有两种形式:既可以按照对象形式解构赋值,也可以按照数组的形式解构赋值

数组的形式解构赋值

js
// 把字符串icoding当做一个数组,[i,c,o,d,i,n,g]
const [x, y, , , , , z] = "icoding";
console.log(x, y, z); // i c g

对象形式的解构赋值

js
// 解构赋值时,对象的属性名为数组的索引值(下标)
// 0 -> i , 1 -> c ...  length 表示数组的长度
const { 0: x, 1: y, length } = "icoding";
console.log(x, y, length); // i c 7

数值和布尔值的解构赋值

用对象模式解构赋值时,如果等号右边是数值或布尔值,是会先转为对象,再用参于对象的解构赋值

js
let { x = 2, toFixed } = 124;
console.log(x); // 2
console.log(toFixed); // ƒ toFixed() { [native code] }

// 上面代码  let { x = 2, toFixed } = 124   等价于下面代码
let { x = 2, toFixed } = new Number(124);
// new Number(124) 对象如下图

Released under the MIT License.