javascript 创建新数组而不影响旧数组的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14498739/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 21:47:49  来源:igfitidea点击:

Create new array without impacting values from old array

javascript

提问by London

I'm trying to create a copy of existing array and remove some items from array copy without impacting the original. I've tried this :

我正在尝试创建现有数组的副本并从数组副本中删除一些项目而不影响原始数组。我试过这个:

var new_arr = old_arr; //when I remove from new array the items from old array are also removed

How do I create entirely new copy of the existing array?

如何创建现有数组的全新副本?

Update :

更新 :

When I do this :

当我这样做时:

var new_arr = old_arr.slice();

then later :

然后:

new_arr[0].shift();
new_arr[1].shift();

The items from old_array get removed. This is a two dimensional array.

old_array 中的项目被删除。这是一个二维数组。

回答by sourcecode

You can use twomethods, this:

您可以使用两种方法,即:

function clone (src) {
    return JSON.parse(JSON.stringify(src));
}

or this:

或这个:

var newArray = oldArray.slice();

回答by Koste

Using Yoshi answer you can extend Array prototype (just a simple helper):

使用 Yoshi 答案,您可以扩展 Array 原型(只是一个简单的帮手):

Array.prototype.clone = function() { 
      return this.slice(0); 
}

回答by Bojoer

A newer solution to do this is to use 'from' like this:

一个较新的解决方案是使用“from”,如下所示:

const newArr = Array.from(oldArr);

But this is a shallow copy and if nested elements are mutated they will project in the new created array with from. Best solution then would be to use

但这是一个浅拷贝,如果嵌套元素发生变异,它们将使用 from 投影到新创建的数组中。最好的解决方案是使用

const newArr = JSON.parse(JSON.stringify(oldArr));

but also that method doesn't ensure all. If for example an element of the array contains a function like n => ++n then it will be null after using the JSON methods so best solution is deepClone and for that full explanation I refer to

但该方法并不能确保全部。例如,如果数组的一个元素包含一个像 n => ++n 这样的函数,那么在使用 JSON 方法后它将为空,所以最好的解决方案是 deepClone,对于完整的解释,我参考

Creating JavaScript Arrays

创建 JavaScript 数组