1. 数组,对象,传参解构
1)数组解构
- 左边是右边的模板
let [a, b, c,] = [1, 2, 3]
console.log(a, b, c) - 用…代替很多
[a, b, …c] = [1, 2, 3, 4, 5, 6];
console.log(a, b, …c) - 用,,,代替数值,如果只需要其中的一个
[, , , a, ,] = [1, 2, 3, 4, 5, 6]
console.log(a); - 交换解析
[a, b] = [b, a]
2) 对象解构
let item = { id: 10, name: “mobiltelephone” };
let id = item.id;
let name = item.name;
console.log("id = %d, name = %s", id, name);
3)传参解构
- 数组传参
let sum = ([a, b]) => a + b;
console.log(sum([10, 20])); - 对象传参
let getUser = ({ name, email }) => [name, email];
console.log(getUser({name: “Peter”, email: “admin@abc.com”}));
2. 访问器属性的get,set
- get: 访问器属性的读取操作
- set: 访问器属性的写的操作
const product = {
data.[
{id: 1, name: “computer”, price: 1000, num: 5 },
{id: 2, name: “camera”, price: 2000, num: 5 },
],
getAmounts(){
return this.data.reduce((t, c) => (t += c.price c.num), 0);
},
};
console.log(“sum = %d dollas”, product.getAmounts());
get total () {
return this.data.reduce((t, c) => (t += c.price c.num), 0);
访问器属性的的优先级高于同名的普通属性
let user = {data: {name},
get name() {
return this.data.name;
};
set name(v) {
this.data.name = v;
},
};
user.name = "Peter";
console.log(user.name);