且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在javascript中没有对象引用的情况下将对象数组复制到另一个数组(深度复制)

更新时间:2022-06-08 16:12:42

让我理解:您不希望拥有一个新数组,而是想为数组本身中存在的所有对象创建一个新实例吗?因此,如果您修改temp数组中的对象之一,那么更改不会传播到主数组中?

Let me understand: you don't want just have a new array, but you want to create a new instance for all objects are present in the array itself? So if you modify one of the objects in the temp array, that changes is not propagated to the main array?

如果是这种情况,则取决于您在主数组中保留的值.如果这些对象是简单对象,并且可以使用JSON进行序列化,那么最快的方法是:

If it's the case, it depends by the values you're keeping in the main array. If these objects are simple objects, and they can be serialized in JSON, then the quickest way is:

var tempArray = JSON.parse(JSON.stringify(mainArray));

如果您有更复杂的对象(例如由您自己的构造函数创建的实例,html节点等),则需要一种专门的方法.

If you have more complex objects (like instances created by some your own constructors, html nodes, etc) then you need an approach ad hoc.

如果newObjectCreation上没有任何方法,则可以使用JSON,但是构造函数将不同.否则,您必须手动进行复制:

If you don't have any methods on your newObjectCreation, you could use JSON, however the constructor won't be the same. Otherwise you have to do the copy manually:

var tempArray = [];
for (var i = 0, item; item = mainArray[i++];) {
    tempArray[i] = new newObjectCreation(item.localIP, item.remoteIP, item.areaId);
}