Home > Article > Web Front-end > How to copy an object in js? (Picture and text tutorial)
The following is what I have compiled for you on how to copy an object in js. Interested students can take a look.
Method 1:
Traverse the properties of the original object and assign them to a new object.
//深复制对象方法 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; //arguments.callee 在哪一个函数中运行,它就代表哪个函数, 一般用在匿名函数中。 newObj[key] = typeof val === 'object' ? cloneObj(val): val; } return newObj; }; //测试 var obj = {a:function(){console.log(this.b.c)},b:{c:1}},//设置一个对象 newObj = cloneObj(obj);//复制对象 newObj.b.c=2;//给新对象赋新值 obj.a();//1,不受影响 newObj.a();//2
Method 2:
Serialize the object and then 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);
Method 3:
For the method of array object, 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);
The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.
Related articles:
JS retains two decimal places for input number verification code
JS retains one digit and moves it backward Unless the number
JS refresh page method summary
The above is the detailed content of How to copy an object in js? (Picture and text tutorial). For more information, please follow other related articles on the PHP Chinese website!