如果我们想把一个属性赋值给另一个名字的变量,比如把 options.width
属性赋值给变量 w
,那么我们可以使用冒号来指定
let options = {
title: "Menu",
width: 100,
height: 200
};
// { sourceProperty: targetVariable }
let {width: w, height: h, title} = options;
// width -> w
// height -> h
// title -> title
console.log(title); // Menu
console.log(w); // 100
console.log(h); // 200
对于可能缺失的属性,我们可以使用 "=" 设置默认值,如下所示:
let options = {
title: "Menu"
};
let {width = 100, height = 200, title} = options;
alert(title); // Menu
alert(width); // 100
alert(height); // 200
就像数组或函数参数一样,默认值可以是任意表达式甚至可以是函数调用。它们只会在未提供对应的值时才会被计算/调用。
在下面的代码中,prompt
提示输入 width
值,但不会提示输入 title
值:
let options = {
title: "Menu"
};
let {width = prompt("width?"), title = prompt("title?")} = options;
alert(title); // Menu
alert(width); //(无论 prompt 的结果是什么
如果对象拥有的属性数量比我们提供的变量数量还多,该怎么办?我们可以只取其中的某一些属性,然后把“剩余的”赋值到其他地方吗?
我们可以使用剩余模式(pattern),就像我们对数组那样。一些较旧的浏览器不支持此功能(例如,使用 Babel 对其进行填充),但可以在现代浏览器中使用。
看起来就像这样:
let options = {
title: "Menu",
height: 200,
width: 100
};
// title = 名为 title 的属性
// rest = 存有剩余属性的对象
let {title, ...rest} = options;
// 现在 title="Menu", rest={height: 200, width: 100}
alert(rest.height); // 200
alert(rest.width); // 100
let options = {
size: {
width: 100,
height: 200
},
items: ["Cake", "Donut"],
extra: true
};
// 为了清晰起见,解构赋值语句被写成多行的形式
let {
size: { // 把 size 赋值到这里
width,
height
},
items: [item1, item2], // 把 items 赋值到这里
title = "Menu" // 在对象中不存在(使用默认值)
} = options;
alert(title); // Menu
alert(width); // 100
alert(height); // 200
alert(item1); // Cake
alert(item2); // Donut