ES6 - 解构赋值

66 阅读1分钟

ECMAScript 6 入门

数组的解构赋值

let [a, b, c] = [1, 2, 3];
let [bar, foo] = [1]; // 解构不成功,变量的值就等于 undefined
let [x, y] = [1, 2, 3]; // 不完全解构
let [x, y = "b"] = ["a"]; // 设置默认值 x='a', y='b'
let [x = 1] = [undefined]; // x=1 ES6 内部使用严格相等运算符 === undefined,默认值才会生效

对象的解构赋值

let { foo, bar } = { foo: "aaa", bar: "bbb" };
let { foo } = { bar: "baz" }; // 解构失败,变量的值等于undefined
var { x = 3 } = {}; // 默认值

字符串的解构赋值

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

const [a, b, c, d, e] = "hello";
// 类似数组的对象都有一个length属性,因此还可以对这个属性解构赋值
let { length: len } = "hello"; // len 5

数值和布尔值的解构赋值

解构赋值时,如果等号右边是数值和布尔值,则会先转为对象。

解构赋值的规则是,只要等号右边的值不是对象或数组,就先将其转为对象

let { toString: s } = 123;
s === Number.prototype.toString; // true

let { toString: s } = true;
s === Boolean.prototype.toString; // true

// undefined 和 null 无法转为对象,所以对它们进行解构赋值,会报错
let { prop: x } = undefined; // TypeError
let { prop: y } = null; // TypeError