2012-03-20 17 views
0

只要看看代碼,你就會明白我的意思:的JavaScript創建使用的備份陣列

​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 
+1

可能的重複[有沒有方法在jQuery中克隆數組?](http://stackoverflow.com/questions/3775480/is-there-a-method-to-clone-an-array-in- jQuery) - 儘管在標題/問題中使用了jQuery,但解決方案並不是jQuery相關的。 – 2012-03-20 10:46:22

+0

@FelixKling對不起,我遇到過這個重複。每個人都應該投票結束。 – noob 2012-03-20 10:56:38

回答

3

你需要讓你的陣列的真實副本,而不是隻使用一個參考:

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] 

MDN的單據上slice - 方法

+1

不錯,打我吧! :) – ChrisR 2012-03-20 10:48:55

1

不JavaScript使用指針數組? ​​var a = aBackup;應該複製一份嗎?否則結果對我來說似乎是正常的...

1

一個數組是一個引用類型的對象,因此對它進行的更改將更改它指向的底層值,a和aBackup將指向相同的值,並且更改做出一個會改變aBackup也。

1

這是因爲當你這樣做,你是不製作數組的副本,但實際上是對原始數組的引用。

var a IS aBackup; // if you will 

當您需要做的是克隆備份陣列。