How can I make a copy of an object in JavaScript?

This question already has an answer here:

  • How do I correctly clone a JavaScript object? 54 answers

  • You will have to map each property to the new array:

    Simple one level clone can be made like this:

    function clone(a, b) {
        var prop;
        for( prop in b ) {
            b[prop] = a;
        }
    }
    

    This will clone all properties from b to a . But keep all other properties in a :

    var a = {a: 9, c: 1},
        b = {a: 1, b: 1};
    
    copy(a, b); // {a: 1, b: 1, c: 1}
    

    Deep Clone Object:

    The above example will work when dealing with single level objects, but will make a confusion when multiply levels is present, take a look at this example:

    var a = {},
        b = { a: { a: 1 } }
    
    clone(a, b);
    
    a.a.a = 2; 
    console.log(a); // { a: { a: 2 } }
    console.log(b); // { a: { a: 2 } }
    

    The above example proves that the object inside aa is the same as the one inside ba .

    链接地址: http://www.djcxy.com/p/24778.html

    上一篇: 如何在javascript / vuejs中创建对象的副本

    下一篇: 我怎样才能在JavaScript中制作一个对象的副本?