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
noob
  • 8,982
  • 4
  • 37
  • 65
  • 1
    possible duplicate of [Is there a method to clone an array in jQuery?](http://stackoverflow.com/questions/3775480/is-there-a-method-to-clone-an-array-in-jquery) -- despite the term jQuery in the title/question, the solutions are not jQuery related. – Felix Kling Mar 20 '12 at 10:46
  • @FelixKling sorry I'vent seen this duplicate. Everyone should vote to close. – noob Mar 20 '12 at 10:56

4 Answers4

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

m90
  • 11,434
  • 13
  • 62
  • 112
1

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

Vinze
  • 2,549
  • 3
  • 22
  • 23
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.

ianaldo21
  • 679
  • 4
  • 10
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.

Tim B James
  • 20,084
  • 4
  • 73
  • 103