美文网首页
ES5、ES6对象合并方法大全

ES5、ES6对象合并方法大全

作者: 泪滴在琴上 | 来源:发表于2023-03-01 16:05 被阅读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"}
    

    相关文章

      网友评论

          本文标题:ES5、ES6对象合并方法大全

          本文链接:https://www.haomeiwen.com/subject/lsfdldtx.html