Populating another array from array - Javascript

Viewed 106948

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

9 Answers

With ES6+ you can simply do this

const original = [1, 2, 3];
const newArray = [...original];

The documentation for spread syntax is here

To check, run this small code on dev console

const k = [1, 2];
const l = k
k === l
> true
const m = [...k]
m
> [1, 2]
k === m
> false

Actually I've tried just this:

const original = [1, 2, 3];
const newArray = original;

and it works!

Related