属性简写
let a = 1; let obj = { a } console.log(obj) //{a:1}
可计算的属性值
let count = 0 function addcount(key) { return `${key}_${count++}` } const nameKey = 'name'; const agekey = "age"; const jobKey = "job"; let person = { [addcount(nameKey)]: 'Matt', [addcount(agekey)]: 27, [addcount(jobKey)]: '小明' } console.log(person) //{name_0:'Matt',age_1,27,job_2:'小明'} console.log(nameKey) //name、
简写的方法名
let obj2 = { // sayName: function (name) { // console.log(name) // } // 简写 sayName(name) { console.log(name) } } obj2.sayName('执行了')
解构赋值
可以设置默认值,对象中属性值为undefined或为空时,默认值生效
【注意】:直接解构null或undefined会抛出错误
数组解构赋值
let [a,b]=[1,2] //交换两个变量的值 let[a,b]=[b,a] //扩展运算符的运用 let[a,...b]=[1,2,3] //有默认值 右侧的参数等于undefined,默认值生效 let[a=3,b]=[1,2]
对象解构赋值
let {a,b}={a:1,b:2} //等价于 let {a:a,b:b}={a:1,b:2}; let{a,...b}={a:1,b:2,c:3}
嵌套解构
可以通过嵌套解构复制对象数组
let person = { name: '小红', age: 12, say: { talk: '脱口秀' } }; let personCopy = {}; ({ name: personCopy.name, age: personCopy.age, say: personCopy.say } = person) console.log(personCopy) let { say: { talk } } = person; console.log(talk) // "脱口秀"
参考上下文匹配
//在参数列表中进行解构赋值 let person = { name: '小红', age: 12 }; function woman(color, { name, age }, sex) { //对参数解构赋值不会影响arguments对象 console.log(arguments) console.log(name, age) } woman('red', person, '女')