0

I need to duplicate and manipulate an array variable, but for some reason when I push a value into the newly created array it is pushing the value into the original array.

function testing (point) {
    var newArray = currentChain;
    newArray.push(point);
}

In this situation, point is being added to the currentChain variable. Note that nowhere am I setting currentChain equal to newArray and there are no other variables in the script called newArray. Why would it be behaving this way?

1
  • Javascript (like Java and many other languages) uses call-by-sharing for objects, so newArray and currentChain point to the same array object Commented Oct 10, 2014 at 16:44

2 Answers 2

2

To fix this you need to clone your array. For example by using slice method:

var newArray = currentChain.slice();

This happens because your newArray is a pointer to currentChain Array.

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

Comments

1

Because both newArray and currentChain share the same reference, so changing one affects the other too.

Use newArray = [] to avoid this, since your naming of the array means so.

1 Comment

"Note that no where am I setting currentChain equal to newArray" ;-)

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.