When js is dealing with complex data, it may involve the copying of reference type objects or arrays. The following are two methods of copying objects or arrays:
1. Using the method that comes with jquery, the call is simple and convenient
// Shallow copy (only copy the values at the root level of the object) var newObject = jQuery.extend({}, oldObject); // deep copy (will copy the entire (including root node and child nodes) object value) var newObject = jQuery.extend(true, {}, oldObject);
Second, you can copy layer by layer by js loop, as follows
// Shallow copy (only copy the values of the object root level)
var old_obj = {a:{b:50}}; function copyBoot(obj){ var newobj = {}; for ( var attr in obj) { newobj[attr] = obj[attr]; } return newobj; } var obj2 = copyBoot(obj); obj2.a.b = 20; alert(obj.a.b);
// deep copy (will copy the entire (including root node and child nodes) object value)
var obj = {a:{b:50}}; function copyAll(obj){ if(typeof obj != 'object'){ return obj; } var newobj = {}; for ( var attr in obj) { newobj[attr] = copyAll(obj[attr]); } return newobj; } var obj2 = copyAll(obj); obj2.a.b = 20; alert(obj.a.b);