JavaScript中,对象解构(Object Destructuring)是一种从对象或数组中提取元素的新方法。
对象解构
ES6 版本之前:
const role = {
lv: 9,
name: 'tom',
coin: 112
}
const temp_lv = role.lv;
const temp_name = role.name;
const temp_coin = role.coin;使用对象解构的相同示例:
const role = {
lv: 9,
name: 'tom',
coin: 112
}
const {lv: temp_lv, name: temp_name, coin: temp_coin} = role;可以看出,使用对象解构,我们在一行代码中提取了对象内的所有元素。
如果希望新变量与对象的属性具有相同的名称,可以删除冒号:
const {lv:lv} = role;
// 相当于
const {lv} = role;数组解构
S6 版本之前:
const list = ['a', 'b', 'c'];
const temp_a = list[0];
const temp_b = list[1];
const temp_c = list[2];使用对象解构的相同示例:
const list = ['a', 'b', 'c'];
const [temp_a, temp_b, temp_c] = list;