问题
Hi i have use the following code to create the object
var parent = {};
parent["Task name"] = "Task " + ++x;
parent["Start time"] = "01/03/2013";
parent["End time"] = "01/08/2013";
parent["Duration"] = "5 days";
parent["Status"] = Math.round(Math.random() * 100);
How to clone / take the copy of the object using JavaScript Code . Is there any other way to achieve this?
回答1:
The simplest way to clone an object is using the following function:
function clone(a){var b=function(){};b.prototype=a;return new b;}
This creates a basic copy of the object, do note though that this does not create a deep copy, only a shallow one.
回答2:
Try this with jQuery:
var parent = {};
parent["Task name"] = "Task " + ++x;
parent["Start time"] = "01/03/2013";
parent["End time"] = "01/08/2013";
parent["Duration"] = "5 days";
parent["Status"] = Math.round(Math.random() * 100);
var newObj = jQuery.extend(true, {}, parent);
回答3:
The most basic way is as follows :
var clone = {};
for (var k in parent) {
clone[k] = parent[k];
}
Works in this case since all values are of primitive types.
来源:https://stackoverflow.com/questions/20738822/cloning-the-object-in-javascript