我正在研究一個項目,其中有一個數組變量突然包含與另一個相同的問題。隨着懶惰的人的警告提示的幫助下,我已經縮小的問題降到這段代碼,這裏的一切突然出錯:鏈接在一起的JavaScript變量沒有很好的理由
// The array "data" is the result of a JSON request - this works fine..
// "data" is a two-dimensional array.
allShowsVars = data.slice();
allShowsVars.sort(function(a, b) {
var aL = a[1].toLowerCase(), bL = b[1].toLowerCase();
if(aL < bL) return -1;
else if(aL > bL) return 1;
else return 0;
});
// At this moment, the allShowsVars variable holds the right contents from the data array..
showsVars = allShowsVars.slice(); // Here, we make a copy of allShowsVars..
for(var iS = 0, sPos; typeof showsVars[iS] != 'undefined'; iS++) {
sPos = showsVars[iS][1].indexOf(" - Season ");
if(sPos != -1) {
showsVars[iS][1] = showsVars[iS][1].slice(0,sPos);
if(iS > 0) {
if(showsVars[(iS-1)][1] == showsVars[iS][1]) showsVars.splice(iS,1);
iS--;
}
}
}
// I changed showsVars in the above for loop, cutting out " - Season ......" in a lot of entries.
現在,allShowsVars也有新的,從showsVars改變的內容。爲什麼??? 變量沒有鏈接在一起! 我在想我錯過了某處明顯的東西。我只是需要一個聰明的人看到它:)
'slice()'拷貝數組,但不是其中的值。 'showsVars [x]'和'allShowsVars [x]'仍然指向同一個對象。 – georg 2014-09-25 08:09:22
非常感謝。我錯過了那個小細節。 – markj 2014-09-25 08:56:03