javascript Javascript将数组复制到新数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15722433/
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-27 01:51:05  来源:igfitidea点击:

Javascript copy array to new array

javascript

提问by joedborg

I want to form an array from an existing array so I can modify the new array without affecting the old. I realise arrays are mutable and this is why the new array affects the old.

我想从现有数组形成一个数组,这样我就可以在不影响旧数组的情况下修改新数组。我意识到数组是可变的,这就是新数组影响旧数组的原因。

E.g.

例如

old = ["Apples", "Bananas"];
new = old;

new.reverse();

Old has also been reversed.

旧的也被颠倒了。

In Python, I can just do new = list(old), but doing new = new Array(old);puts the old list inside a list.

在 Python 中,我可以只做new = list(old),但做new = new Array(old);将旧列表放入列表中。

回答by Benjamin Gruenbaum

You can use the .slicemethod:

您可以使用以下.slice方法:

var old = ["Apples", "Bananas"];
var newArr = old.slice(0);
newArr.reverse(); 
// now newArr is ["Bananas", "Apples"] and old is ["Apples", "Bananas"]

Array.prototype.slice returns a shallow copy of a portion of an array. Giving it 0 as the first parameter means you are returning a copy of all the elements (starting at index 0 that is)

Array.prototype.slice 返回数组一部分的浅拷贝。给它 0 作为第一个参数意味着您将返回所有元素的副本(从索引 0 开始)

回答by JaredPar

Try the following

尝试以下

newArray = oldArray.slice(0);