Methods for copying objects in Javascript: 1. Traverse the properties of the original object and assign them to a new object; 2. Change the object into a string, and then into a json object; 3. Concat an empty object Array; 4. Implement deep copy of object through expansion operator; 5. Implement deep copy of array through ES6 expansion operator.
The operating environment of this article: windows7 system, javascript version 1.8.5, Dell G3 computer.
How to copy an object in js?
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:
1). First change the object into a string, and then into a json object to prevent the object pointer from pointing to the problem, which is a deep copy
2). Properties of undefined and function types will be ignored, while properties of Date type will be converted to strings
var obj = {a:1,b:2} var newObj = JSON.parse(JSON.stringify(obj)); newObj.a=3; console.log(obj); console.log(newObj);
Method 3:
Methods for 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);
Method 4:
Extension operator to implement deep copy of the object
var obj = { name: 'FungLeo', sex: 'man', old: '18'}var { ...obj2 } = obj obj.old = '22'console.log(obj) console.log(obj2)
Method 5:
ES6 expansion operator implements deep copy of array
var arr = [1,2,3,4,5]var [ ...arr2 ] = arr arr[2] = 5console.log(arr) console.log(arr2)
javascript Advanced Tutorial 》
The above is the detailed content of How to copy objects in Javascript. For more information, please follow other related articles on the PHP Chinese website!