对象相关笔记
2018-08-21 本文已影响0人
UmustHU
对象简洁写法
let name = 'Bob';
let age = 15;
//老写法
let person = {
name:name,
age:age,
popMsg:function(){
console.log(this.name,this.age)
}
};
//简洁写法
let person = {
name,
age,
popMsg(){
console.log(this.name,this.age)
}
};
Object.assign()
将对象进行合并,并且返回新对象,注意:参数中后面的对象如果与前面对象数据重合,则会把前面的对象数据覆盖;
let json1 = {name:'bob'};
let json2 = {age:18};
let json3 = {sex:0};
let json4 = Object.assign({},json1,json2,json3);
console.log(json4);
//返回结果
{ name: 'bob', age: 18, sex: 0 }
//测试覆盖
let json1 = {name:'bob'};
let json2 = {name:'Lily',age:18};//数据和json1中有重复
let json3 = {sex:0};
let json4 = Object.assign({},json1,json2,json3);
console.log(json4);
//返回结果
{ name: 'Lily', age: 18, sex: 0 }
Object.keys(),Object.values(),Object.entries()
let json = {name:'Bob',age:18,sex:18};
console.log(Object.keys(json));
console.log(Object.values(json));
console.log(Object.entries(json));
//返回结果
[ 'name', 'age', 'sex' ]
[ 'Bob', 18, 18 ]
[ [ 'name', 'Bob' ], [ 'age', 18 ], [ 'sex', 18 ] ]