var a=[1,2,3];
var b=a;
b.push(4,5);
console.log(b);
console.log(a);
I want a value as [1,2,3]. But it printing [1,2,3,4,5] How can I achieve this. Please help. Thanks in advance
var a=[1,2,3];
var b=a;
b.push(4,5);
console.log(b);
console.log(a);
I want a value as [1,2,3]. But it printing [1,2,3,4,5] How can I achieve this. Please help. Thanks in advance
You are assigning the array's object reference to another one variable. But here what you want to do is to copy the array to create a new instance.
var a=[1,2,3];
var b= a.slice(0);
b.push(4,5);
console.log(b); //[1,2,3,4,5]
console.log(a); //[1,2,3]
Array.prototype.slice
will create a copy of the original array when the start value passed along is 0
. But if you are really concerned about passing a hard coded value, use the call
's variant.
var b= [].slice.call(a);
Let's talk a bit about memory ...
a
is saved in memory, for example, at the address of 123
when you tell in your code to make b = a
it just refer to the same a
at the address 123
so they both have the same place in memory so when you change any of them you change the other
... So what you can do is to create another place in memory for your second array by one of these methods
var b= a.slice(0);
or
var b= JSON.stringify(JSON.parse(a));
or
var b = [].concat(a);