我正在開發一個練習項目 - 一個Dota相關的迷你遊戲。在循環中發生不明原因的數組排序
http://jsfiddle.net/easwee/MwGsd/
你正在的3種試劑組合召喚(調用)一個咒語。
我有一個數組包含所有可能的拼寫組合和另一個空陣列,它記錄按鍵並將按下的試劑存儲在該數組中。 你總是需要3種試劑來創造咒語 - 試劑順序無關緊要。
到目前爲止,所有的作品,但我encoutering一個問題,一旦我開始比較在輸入的試劑陣列的法術列表數組:
我用下面的比較功能:
function compareArrays(arr1, arr2) {
return arr1.sort().toString() === arr2.toString()
}
我排序的陣列和在下面的函數比較(reagentStack
- 包含在輸入的試劑):
function updateSpellList(reagentStack){
for(var spell in spellList) {
var compareStack = reagentStack;
compareSpell = spellList[spell];
console.log(spell);
console.log('compareStack: ' + compareStack + '/compareSpell: ' + compareSpell + '/reagentStack: ' + reagentStack); // check this log in fiddle console
console.log('---');
if(compareArrays(compareStack, compareSpell)) {
invokedSpell = spell;
console.log('Invoked spell: ' + invokedSpell);
break;
}
}
}
在examp樂小提琴(here)如果按Q + Q + Ë + [R您創建一個法術組合(在這種情況下icewall)。
它比較一切ok,並遵循我的腳本邏輯(集的compareStack
到reagentStack
,排序compareStack
和compareSpell
陣列和比較),但我不明白爲什麼也種類reagentStack
陣列,因爲我沒有排序它在整個腳本的任何地方?
這是沒有排序的for
循環的第一次迭代,但得到的關於第二次迭代排序,將不再能正確,因爲現在compareStack
比較是越來越設置爲分類reagentStack
而不是原先inputed。
控制檯日誌:
coldsnap
compareStack: quas,quas,exort/compareSpell: quas,quas,quas/reagentStack: quas,quas,exort
---
ghostwalk
compareStack: exort,quas,quas/compareSpell: quas,quas,wex/reagentStack: exort,quas,quas
在第一循環中reagentStack沒有排序上已經排序第二循環 - 爲什麼?
哦,是的,這就是它 - 不知道它得到的傳遞這樣。感謝幫助! – easwee
@easwee btw我會在比較函數中使用'JSON.stringify()'over'toString()'。如果你的數組包含','更穩定。 – Sirko
指出 - 感謝寶貴的提示! – easwee