javascript 使一个数组完全等于另一个
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17907233/
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
Making one array exactly equal to another
提问by jskidd3
I have two arrays:
我有两个数组:
var array1 = [1, 2, 3];
var array2 = [4, 5, 6];
I want array 1 to be exactly equal to array 2. I've been told I can't simply do:
我希望数组 1 与数组 2 完全相等。有人告诉我我不能简单地做:
array1 = array2;
If I can't do this, how can I make array1 equal to array2?
如果我不能这样做,我怎样才能使 array1 等于 array2?
Thanks
谢谢
回答by Pawel Miech
If you just need a copy of the elements of an array you can simply use slice like this:
如果你只需要一个数组元素的副本,你可以简单地使用 slice 像这样:
a = [1,2,3]
copyArray = a.slice(0)
[1 , 2 , 3]
As for why you should not use assignement here look at this example:
至于为什么你不应该在这里使用assignment看这个例子:
a = [1,2,3]
b = a
a.push(99)
a
[1,2,3,99]
b
[1,2,3,99]
If you copy an array you don't have this problem:
如果你复制一个数组,你就没有这个问题:
a = [1,2,3]
b = a.slice(0)
a.push(888)
a
[1,2,3,888]
b
[1,2,3]
回答by DanielX2010
For a deep copy of your array, do this (REFERENCE):
对于数组的深层副本,请执行以下操作(参考):
function deepCopy(obj) {
if (Object.prototype.toString.call(obj) === '[object Array]') {
var out = [], i = 0, len = obj.length;
for ( ; i < len; i++ ) {
out[i] = arguments.callee(obj[i]);
}
return out;
}
if (typeof obj === 'object') {
var out = {}, i;
for ( i in obj ) {
out[i] = arguments.callee(obj[i]);
}
return out;
}
return obj;
}
回答by detman
This will do the trick:
这将解决问题:
var clone = originalArray.slice(0);