-2

I have the following code that copy variable value then change its value.

var a = [{name: 'John Doe'}];
var b = a;

document.write(b[0].name + '<br />');
document.write(a[0].name + '<br /><br />');

b[0].name = 'Jane Doe';

document.write(b[0].name + '<br />');
document.write(a[0].name + '<br />');

But somehow that also change first variable value

How do I make variable A to keep its value?

ilmansg
  • 99
  • 8
  • 1
    You have to deeply clone `a`, one way to do it is `var b = JSON.parse(JSON.stringify(a))` – Mauricio Poppe Jun 01 '16 at 22:08
  • Possible dupe of: http://stackoverflow.com/questions/15722433/javascript-copy-array-to-new-array – Oisin Jun 01 '16 at 22:08
  • Variable a is being passed into b by reference. Since a and b have the same reference, whenever you change anything on one it also changes the other. To prevent this you'll need to do a deep copy of a onto b, copying all of the individual properties. – nurdyguy Jun 01 '16 at 22:08
  • Objects (including Arrays) are assigned by reference in JavaScript. You must manually copy them if you need to maintain two separate `.name` values. – Mulan Jun 01 '16 at 22:09
  • Sorry if its duplicated, I dont know the correct terms when I search the answer before :( – ilmansg Jun 01 '16 at 22:24

1 Answers1

1

You are just assigning the a-reference to b. What you may want to do is copying the array so that changes to a are not reflected to b. See this thread for the different assignments in JavaScript.

Take also a look at fastest way to duplicate an array. It's about the speed of different array copy methods. Quick answer is:

var b = a.slice();

The slice() method creates a new array with the same elements than the original one. But be careful it's only a shallow copy.

You could also use the JSON.stringify() and JSON.parse()methods for doing a deep copy.

Community
  • 1
  • 1
CodeLionX
  • 53
  • 1
  • 4