0

I am new to JavaScript here. I am trying to create a variable duplicated from a object property. When I make changes to the new variable, the original variable is also changed. How can I break the link between the two variables?

For instance,

var a = {};
a.data = ["a", "b", "c", "d"];
var b = a.data;
b.splice(0,1);

The output looks like the following.

> b
> ["b", "c", "d"]
> a.data
> ["b", "c", "d"]

What I expect is this.

> b
> ["b", "c", "d"]
> a.data
> ["a", "b", "c", "d"]
Boxuan
  • 4,937
  • 6
  • 37
  • 73
  • 1
    possible duplicate of [Most efficient way to clone an object?](http://stackoverflow.com/questions/122102/most-efficient-way-to-clone-an-object) – Quentin Apr 18 '14 at 14:33

1 Answers1

5

Clone the array :

var b = a.data.slice();
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758