user2123244
user2123244

Reputation: 99

Node/Javascript setting object property to array not working?

var arr = new Array();
arr[0] = "a";
var ob = new Object();
ob.prop = arr;
ob.prop[0] = "b";
//Console log arr[0] returns b

for some reason, the arr array is being changed when I change ob.prop ?

What am I missing?

Upvotes: 1

Views: 268

Answers (2)

Nick Mitchinson
Nick Mitchinson

Reputation: 5480

As Jorge mentioned, this is happening because obj.prop is just a reference to arr, so arr and obj.prop will point to the same place in memory. So if you change either, the value in memory (which the other is pointing to) changes, thus changing both.

If you're looking to avoid this you need to do a deep copy. This will copy the values of the array into a new array, which obj.prop will point at.

There is a walk-through of how to do this in javascript here.

Upvotes: 1

Jorge Israel Peña
Jorge Israel Peña

Reputation: 38586

As the system pointed out, ob.prop = arr is basically just giving another name for accessing the object referenced by arr. So when you modify ob.prop you are modifying the same object that arr also refers to.

EDIT: For copying an array take a look at this question:

var arrCopy = arr.slice();

Upvotes: 1

Related Questions