Populating another array from array - Javascript
copy-or-clone-javascript-array-object
var a = [ 'apple', 'orange', 'grape' ];
b = a.slice(0);
In ES6 you can use Array.from:
var ar = ["apple","banana","canaple"];
var bar = Array.from(ar);
alert(bar[1]); // alerts 'banana'
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();
You have two problems:
First you need to initialize bar
as an array:
var bar = [];
Then arr
should be ar
in here:
for(i=0;i<arr.length;i++){
Then you'll get alerted your banana :)