tags:

views:

80

answers:

6

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.)

+3  A: 
Daniel Vassallo
yup - exactly it. too used to php sloppiness, forgot to declare the array! thanks for being the first to answer!
ina
+9  A: 

Your code isn't working because you are not initializing bar:

var bar = [];

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 :).

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();
CMS
+1 for suggesting slice.
Daniel
yes +1 for slice - btw does slice work for multidimensional arrays?
ina
ina: it appears you can use a little trick for that! var bar = arr.concat();
Daniel
@ina: `slice` will *shallow copy* the array elements that are objects, could you provide a less simplified example, to see exactly what you want to achieve?
CMS
+1  A: 

You have misspelled variable ar Try this

for(i=0;i<ar.length;i++){
    bar[i]=ar[i];
}
alert(ar[1]);
Codler
yes ty for the pointer - this was not actual code, just brutal simplification typed up too quickly for a jsfiddle
ina
+1  A: 

The problem probably here in the for loop statement:

for(i=0;i<ar.length;i++){
    bar[i]=ar[i];
}
alert(ar[1]);

You need to fix to ar.length instead of arr.length. And it's better to initialize bar as: var bar = [].

Artem Barger
+1  A: 

In your code, the variable arr in the for loop is not the same as your original array ar: you have one too many r.

slebetman
+2  A: 

copy-or-clone-javascript-array-object

Pranay Rana
interesting trick!
ina