Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populating another array from array - Javascript

Tags:

javascript

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

like image 711
ina Avatar asked Aug 09 '10 07:08

ina


People also ask

Can you assign an array to another array in JavaScript?

To append one array to another, use the push() method on the first array, passing it the values of the second array. The push method is used to add one or more elements to the end of an array. The method changes the contents of the original array. Copied!

How do you populate an array in JavaScript?

In JavaScript, you can use the Array. fill() method to populate an array with a zero or any other value like an object or a string. This method replaces all elements in an array with the value you want to populate the array with and returns the modified array.

How do I copy one array to another in JavaScript?

“concat()” is another useful JavaScript method that can assist you in copying array elements. In the concat() method, you can take an empty array and copy the original array elements to it. It will create a fresh copy of the specified array. var array2 = [].


1 Answers

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(); 
like image 179
Christian C. Salvadó Avatar answered Sep 20 '22 13:09

Christian C. Salvadó