复制对象的数组在JavaScript另一个数组(深层副本) [英] Copying an array of objects into another array in javascript (Deep Copy)
本文介绍了复制对象的数组在JavaScript另一个数组(深层副本)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用切片(0)和CONCAT()不工作复制对象的数组在JavaScript另一个数组。
Copying an array of objects into another array in javascript using slice(0) and concat() doesnt work.
我曾尝试以下测试,如果我得到使用此深副本的预期行为。但原阵列也越来越修改后,我做复制数组中的变化。
I have tried the following to test if i get the expected behaviour of deep copy using this. But the original array is also getting modified after i make changes in the copied array.
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)
我怎样才能做一个阵列的深层复制到另一个,这样,如果我在副本阵列改变原始数组不会被修改。
How can i do a deep copy of a array into another, so that the original array is not modified if i make a change in copy array.
推荐答案
尝试
var copy = JSON.parse(JSON.stringify(tags));
这篇关于复制对象的数组在JavaScript另一个数组(深层副本)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文