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.)
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!
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.
“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 = [].
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With