一些常用的对象API
const person = { name: 'zhangsan', age: 12, language: ['java', 'python', 'go'] } console.log(Object.keys(person)) //返回person的所有key console.log(Object.values(person)) //返回person 的所有value console.log(Object.entries(person)) // 以数组形式返回每一个key和value
合并对象, 并都放到第一个对象里边
var a = {name: 'zhangsan'} var b = {age: 12} var c = {language: ['java', 'python', 'go']} Object.assign(a, b, c) console.log(a)
声明对象简写
var name = 'zhanshen' var age = 14 var per = {name: name, age: age} console.log(per) //上边这样key的名字和value的名字一样,就可以如下简写 var p = {name, age} console.log(p)
对象的函数属性简写
const person = { name: 'zhangsan', age: 12, language: ['java', 'python', 'go'], eat: function(food) { console.log("我是"+this.name+", 我在吃"+food) }, eat2: food => console.log("我是"+this.name+", 我在吃"+food), // 这种是箭头函数的写法 eat3: food => console.log("我是"+person.name+", 我在吃"+food), eat4 (food) { console.log("我是"+this.name+", 我在吃"+food) } } person.eat('香蕉') person.eat2('桔子') person.eat3('草莓') person.eat4('香橙')
对象扩展运算符
let per1 = {name: '张三'} let per1_copy = {...per1} // 利用 ... 实现深拷贝 console.log(per1_copy) let age = {age: 12} let name = {name: 'zhangsan'} let person2 = {...name, ...age} // 合并对象 console.log(person2)
如果之前有重复的会覆盖