0
 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

  • `I want a value [1,2,3]` for what? b? a? both? something else? – Jaromanda X Mar 12 '17 at 04:18
  • I want to use a value is [1,2,3] and b value is [1,2,3,4,5]. But I am getting a value is [1,2,3,4,5]. – user1649134 Mar 12 '17 at 04:20
  • Since array work on call by reference[http://stackoverflow.com/questions/6605640/javascript-by-reference-vs-by-value], so you have to use concat method to solve your problem , because concat method create a new array which didn't modify existing array. Solution: var a =[1,2,3]; b = [].concat(a); b.push(4,5); console.log(b); console.log(a) – coder Mar 12 '17 at 04:31

2 Answers2

2

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);
Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130
0

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

Community
  • 1
  • 1
solimanware
  • 2,952
  • 4
  • 20
  • 40