Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
32
rated 0 times [  34] [ 2]  / answers: 1 / hits: 120846  / 14 Years ago, mon, august 9, 2010, 12:00:00

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


More From » javascript

 Answers
5

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();

[#95986] Thursday, August 5, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kinsley

Total Points: 352
Total Questions: 84
Total Answers: 94

Location: Denmark
Member since Tue, Jul 19, 2022
2 Years ago
;