一个正常的代码:
let arr = [1, 2, 3];
let a = arr[0];
let b = arr[1];
let c = arr[2];
console.log(a, b, c);
数组解构:等号左边和等号右边需要一样
let [a,b,c] = [1,2,3];
console.log(a,b,c)
效果是一样的
[a, b, c = "js"] = [1, 2];
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, b, ...c);
// 交换值
let a = 10,
b = 20;
console.log(a, b);
[b, a] = [a, b];
console.log(a, b);
也是一句话 等号左边和右边是一样的
let item = { id: 10, name: "手机" };
let id = item.id;
let name = item.name;
console.log("id=%d, name = %s", id, name);
({id, name}) = ({id:10, name:"电脑"});
let sum = ([a,b]) => a+b;
console.log(sum[30,50])
对象传参
let getUser = ({name,email})=>[name,email];
console.log(getUser({name:"xxxx",email:"admin@php.cn"}))
访问器属性 将一个方法伪装/包装成一个属性
const product = {
data: [
{ id: 100, name: "电脑", price: 5000, num: 5 },
{ id: 100, name: "手机", price: 4000, num: 15 },
{ id: 100, name: "相机", price: 15000, num: 35 },
],
get读取 也叫读操作
get total(){
return this.data.reduce((t,c)=>(t += c.price * c.num), 0);
}
set 访问器属性的写操作
set setPrice(price){
this.data[1].price = price;
}
// 不想用方法,想以属性的方式来获取总金额
console.log("总金额 = %d 元", product.total);
product.setPrice = 8000;
console.log(product.data[1].price);