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.
The first thing I tried, of course, was simply bar = ar; — didn’t work, so I tried manually looping through… still doesn’t work.
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]);
And, here is the fiddle: http://jsfiddle.net/vGycZ/
(The above is a simplification. The actual array is multidimensional.)
Your code isn’t working because you are not initializing
bar:You also forgot to declare your
ivariable, which can be problematic, for example if the code is inside a function,iwill end up being a global variable (always usevar:).But, you can avoid the loop, simply by using the
slicemethod to create a copy of your first array: