Javascript将数组复制到新数组 [英] Javascript copy array to new array
问题描述
我想从现有数组中形成一个数组,这样我就可以修改新数组而不会影响旧数组。我意识到数组是可变的,这就是新数组影响旧数据的原因。
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.
例如
old = ["Apples", "Bananas"];
new = old;
new.reverse();
旧的也被逆转。
在Python中,我可以只执行 new = list(old)
,但是执行 new = new Array(旧);
将旧列表放在列表中。
In Python, I can just do new = list(old)
, but doing new = new Array(old);
puts the old list inside a list.
推荐答案
您可以使用 .slice
方法:
You can use the .slice
method:
var old = ["Apples", "Bananas"];
var newArr = old.slice(0);
newArr.reverse();
// now newArr is ["Bananas", "Apples"] and old is ["Apples", "Bananas"]
Array.prototype.slice返回数组部分的浅表副本。给它0作为第一个参数意味着你要返回所有元素的副本(从索引0开始)
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)
这篇关于Javascript将数组复制到新数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!