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
link|improve this question

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. – Felix Kling Mar 20 at 10:46
@FelixKling sorry I'vent seen this duplicate. Everyone should vote to close. – micha Mar 20 at 10:56
feedback

4 Answers

up vote 3 down vote accepted

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

link|improve this answer
1  
nice, beat me to it! :) – ChrisR Mar 20 at 10:48
feedback

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

link|improve this answer
feedback

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.

link|improve this answer
feedback

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.

link|improve this answer
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.