ES5、ES6对象合并方法大全

2023-03-01  本文已影响0人  泪滴在琴上

ES5:循环遍历

let obj1 = {name:'a',age:18};
let obj2 = {name:'b',gender:'man'};
let obj3 = {};
for(var attr in obj1){
    obj3[attr] = obj1[attr];
}
for(var attr in obj2){
    obj3[attr] = obj2[attr];
}
console.log(obj3);//{name: "b", age: 18, gender: "man"}

ES6:object.assign

let obj1 = {name:'a',age:18};
let obj2 = {name:'b',gender:'man'};
let obj3 = {};
Object.assign(obj3,obj1,obj2);
console.log(obj3);//{name: "b", age: 18, gender: "man"}

ES6:拓展运算

let obj1 = {name:'a',age:18};
let obj2 = {name:'b',gender:'man'};
let obj3 = {...obj1,...obj2};
console.log(obj3);//{name: "b", age: 18, gender: "man"}
上一篇下一篇

猜你喜欢

热点阅读