0

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?

1
  • Well, yes, objects and arrays are always handled "by reference". If you want to make a copy of it, you need to explicitly make a copy. Is your question how to create a copy of an array? Without more concrete code on how these arrays are created we can't help a lot. Commented Aug 31, 2015 at 11:04

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.