user1649134 user1649134 - 1 year ago 42
Javascript Question

How to access variable in Javascript?

var a=[1,2,3];
var b=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

Answer Source

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

 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= [];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download