ES5、ES6对象合并方法大全
日期:2020-05-12
来源:程序思维浏览:5843次
今天跟大家说一下ES5、ES6对象合并的方法:
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"}
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"}
- 上一篇:大牛全面解析js的this指向问题
- 下一篇:js正则表达式知识大全
精品好课