从数组填充另一个数组 - Javascript
我想在JS中做的很简单(将一个数组的值分配给另一个数组),但不知何故,数组 bar
的值似乎没有受到影响一点都不
Very simple thing I am trying to do in JS (assign the values of one array to another), but somehow the array bar
's value doesn't seem affected at all.
我尝试的第一件事当然是 bar = ar;
- 没有用,所以我尝试手动循环...仍然无法正常工作。
The first thing I tried, of course, was simply bar = ar;
-- didn't work, so I tried manually looping through... still doesn't work.
我没有理解Javascript的怪癖!请帮忙!!
I don't grok the quirks of Javascript! Please help!!
var ar=["apple","banana","canaple"];
var bar;
for(i=0;i<ar.length;i++){
bar[i]=ar[i];
}
alert(ar[1]);
而且,这里是小提琴: http://jsfiddle.net/vGycZ/
And, here is the fiddle: http://jsfiddle.net/vGycZ/
(以上是简化。实际的数组是多维的。)
(The above is a simplification. The actual array is multidimensional.)
你的代码无法正常工作,因为你没有初始化 bar
:
Your code isn't working because you are not initializing bar
:
var bar = [];
您也忘记申报 i
变量,这可能有问题,例如,如果代码在函数内, i
将最终成为一个全局变量(总是使用 var
:)。
You also forgot to declare your i
variable, which can be problematic, for example if the code is inside a function, i
will end up being a global variable (always use var
:).
但是,你可以通过使用 slice
方法来创建第一个数组的副本:
But, you can avoid the loop, simply by using the slice
method to create a copy of your first array:
var arr = ["apple","banana","canaple"];
var bar = arr.slice();