我正在研究一个项目,其中有一个数组变量突然包含与另一个相同的问题。随着懒惰的人的警告提示的帮助下,我已经缩小的问题降到这段代码,这里的一切突然出错:链接在一起的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