[英]Array of arrays being mutated with slice, spread, and map
This question has been asked here and more importantly here . 这个问题已经在这里提出,更重要的是在这里提出 。 I tried all the answers and none solved my issue. 我尝试了所有答案,但没有一个解决了我的问题。 It's very basic. 这是非常基本的。
I have the following array. 我有以下数组。 My various attempts at copying do not persist after splicing, or performing any destructive action. 进行拼接或执行任何破坏性操作后,我进行的各种尝试都不会持久。 Even the copies are mutated. 甚至副本都是突变的。 How can I copy this so the original version persists? 我该如何复制它以便原始版本继续存在?
var arrs = [ [ 3 ], [ 7, 4 ], [ 2, 4, 6 ], [ 8, 5, 9, 3 ] ]
var arrsCopy1 = arrs.slice()
var arrsCopy2 = arrs.map(arr => {
return arr
})
var arrsCopy3 = [...arrs]
//test one of the copies
arrsCopy3.forEach(arr => {
return arr.splice(0, arr.length)
})
arrs, arrsCopy1, arrsCopy2, arrsCopy3 => [[],[],[],[]]
Here is a fiddle that demos my problem (using reverse()
instead of splice
) 这是一个小提琴,演示了我的问题(使用reverse()
而不是splice
)
You could do it recursively 您可以递归执行
const copyArr = (element) => {
//If the element is a primitive
if (element !== Object(element)) {
return element;
//The element is an array
} else {
return element.map(subelement => copyArr(subelement));
}
}
尝试使用JSON
方法:
var arrCopy = JSON.parse(JSON.stringify(arr));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.