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.
You have misspelled variable ar Try this
for(i=0;i<ar.length;i++){
bar[i]=ar[i];
}
alert(ar[1]);
The problem probably here in the for loop statement:
for(i=0;i<ar.length;i++){
bar[i]=ar[i];
}
alert(ar[1]);
You need to fix to ar.length
instead of arr.length.
And it's better to initialize bar as: var bar = []
.
In ES6 you can use Array.from:
var ar = ["apple","banana","canaple"];
var bar = Array.from(ar);
alert(bar[1]); // alerts 'banana'
In your code, the variable arr
in the for loop is not the same as your original array ar
: you have one too many r
.
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();
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