在javascript中,使用slice(0)和concat()将对象数组复制到另一个数组中不起作用。
我已经尝试了下面的方法来测试我是否使用它获得了深度复制的预期行为。但在我对复制的数组进行更改后,原始数组也会被修改。
var tags = [];
for(var i=0; i<3; i++) {
tags.push({
sortOrder: i,
type: 'miss'
})
}
for(var tag in tags) {
if(tags[tag].sortOrder == 1) {
tags[tag].type = 'done'
}
}
console.dir(tags)
var copy = tags.slice(0)
console.dir(copy)
copy[0].type = 'test'
console.dir(tags)
var another = tags.concat()
another[0].type = 'miss'
console.dir(tags)
如何将一个数组深度复制到另一个数组中,以便在对复制数组进行更改时不会修改原始数组。
发布于 2015-02-13 00:32:09
试一试
var copy = JSON.parse(JSON.stringify(tags));
发布于 2015-02-13 00:34:46
请尝试以下操作
// Deep copy
var newArray = jQuery.extend(true, [], oldArray);
有关更多详细信息,请查看此问题What is the most efficient way to deep clone an object in JavaScript?
发布于 2018-05-28 01:44:50
https://stackoverflow.com/questions/28482593
复制相似问题