How does js copy an object?

Article excerpt

http://blog.csdn.net/liyujia6636/article/details/52198128

 

method one:

Traverse the properties of the original object and assign them to a new object.

 

//deep copy object method  
var cloneObj = function (obj) {
    var newObj = {};
    if (obj instanceof Array) {
        newObj = [];
    }
    for (var key in obj) {
        var val = obj [key];
        //newObj[key] = typeof val === 'object' ? arguments.callee(val) : val; //in which function the arguments.callee runs, it represents which function, generally used in anonymous functions.
        newObj[key] = typeof val === 'object' ? cloneObj(val): val;
    }
    return newObj;
};
//test  
var obj = {a:function(){console.log(this.bc)},b:{c:1}},//Set an object
newObj = cloneObj(obj);//Copy object
newObj.bc=2;//Assign a new value to the new object
obj.a();//1, not affected
newObj.a();//2

 

Method Two:

Serialize the object and parse it back . If there is a function in the object, it cannot be copied correctly

 

var obj = {a:1,b:2}
var newObj = JSON.parse(JSON.stringify(obj));
newObj.a=3;
console.log(obj);
console.log(newObj);

Note: I personally prefer this method, but only if the browser supports JSON objects .  

 

Method three:

For methods of array objects, use the array method to concat an empty array

var a=[1,2,3];
var b=a;
var c=[].concat(a);
a.push(4);
console.log(b);
console.log(c);

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326801527&siteId=291194637