Aron
Aron

Reputation: 9258

Pass array into array of arrays by value, not reference

I have an array of coordinates (coods), which are therefore smaller arrays, which I want to add new arrays to. I want it to look like this:

[
[0,2],
[0,1],
[0,0]
]

I want to do this by adding a constantly changing variable new to it every time the code runs:

coods.unshift(new);

The only problem is that (as took me forever to discover), when passing a new array into the larger array it is only passing a reference, not the value itself, so I end up having a coods array of:

[
[0,2],
[0,2],
[0,2]
]

How can I fix this?

Upvotes: 0

Views: 51

Answers (1)

Gus Hogg-Blake
Gus Hogg-Blake

Reputation: 2511

You could use coods.unshift(new.slice()) to add a copy of the array. (See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice).

Alternatively there is probably a way of changing the design of the code so that this isn't a problem, but if not then slice is probably the way to go. You may want to use a specific cloning function (several libraries have them, or write your own that uses slice) to make it more semantic though.

Upvotes: 1

Related Questions