Cloning the object in JavaScript [duplicate]

自闭症网瘾萝莉.ら 提交于 2019-12-20 07:09:43

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!