1.对象字面量的增强写法
const name = "why";
const age = 18;
const friend = "friend";
const obj = {
name: name, //原先的写法
age, //属性简写
foo: function () {
console.log(obj.name);
},
getAge() {
//方法的简写
return this.age;
},
[friend + "1"]: "lily", //计算属性
};
obj[friend + "2"] = "koby";
console.log(obj);
2.数组的解构
const names = ["abc", "cba", "bac"];
//数组的解构是按照顺序取值的
const [item1, item2, item3] = names;
console.log(item1, item2, item3); //abc cba bac
//只解构最后一个值
const [, , itemz] = names;
console.log(itemz); //bac
//解构时设置默认值
const [itema, itemb, itemc,itemd] = names;
console.log(itema, itemb, itemc,itemd) //abc cba bac undefined
const [itema1, itemb1, itemc1,itemd1 = 'bbb'] = names;
console.log(itema1, itemb1, itemc1,itemd1) //abc cba bac bbb
//只解构第一个,其余的放在一个数组中
const [item5, ...newNames] = names
console.log(item5, newNames) //abc [ 'cba', 'bac' ]
3.对象的解构
const obj = {
name: "why",
age: 18,
};
//对象的解构是按照键名赋值的,不是按照顺序赋值的
const { age, name } = obj;
console.log(name, age); //why 18
//可以不以键名作为变量的名字,自定义变量名
const { age: newAge } = obj;
console.log(newAge); // 18
//给设置默认值
const { address: newAddress = "北京市" } = obj;
console.log(newAddress); //北京市
function foo({name, age}) {
console.log(name, age) //why 18
}
foo(obj)
非常感谢王红元老师的深入JavaScript高级语法让我学习到很多 JavaScript
的知识
网友评论