Cloning the object in JavaScript [duplicate]

爷,独闯天下 提交于 2019-12-02 09:38:32

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.

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);

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.

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