0

Just look at the code and you'll understand what I mean:

​var aBackup = [3, 4]; // backup array
​​var a = aBackup; // array to work with is set to backup array
a[0]--; // working with array..
a = aBackup; // array o work with will be rested
console.log(a);  // returns [2, 4] but should return [3, 4]
console.log(aBackup);​ // returns [2, 4] too​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​  but should return [3, 4] too
2
  • 1
    possible duplicate of Is there a method to clone an array in jQuery? -- despite the term jQuery in the title/question, the solutions are not jQuery related. Commented Mar 20, 2012 at 10:46
  • @FelixKling sorry I'vent seen this duplicate. Everyone should vote to close. Commented Mar 20, 2012 at 10:56

4 Answers 4

3

You need to make real copies of your Arrays instead of just using a reference:

var aBackup = [3, 4]; // backup array
var a = aBackup.slice(0); // "clones" the current state of aBackup into a
a[0]--; // working with array..
a = aBackup.slice(0); // "clones" the current state of aBackup into a 
console.log(a);  // returns [3, 4] 
console.log(aBackup); // returns [3, 4]

See MDN for documentation on the slice-method

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

Comments

1

Doesn't javascript uses pointer for arrays ? Should ​​var a = aBackup; do a copy ? otherwise the results seems normal to me...

Comments

1

An array is a reference type of object, so changes made to it will change the underlying value it points to, a and aBackup will point to the same value, and a change made to a will change aBackup aswell.

Comments

1

It is because when you do this, you are not making a copy of the array, but infact a reference to the original array.

var a IS aBackup; // if you will

When you need to do is clone the backup array.

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.