此問題涉及我的算法以及它爲什麼不起作用。更具體地說,我想知道如何改進以做我想做的事情。這就是爲什麼它與建議的重複問題不同。基於屬性值對對象數組排序(int)
我想創建一個函數,它基於屬性值(int),他們都共同共享,「indexFound」分類對象的數組。正如你可能會懷疑的那樣,我試圖在數組的開頭放置一個indexFound值較低的元素。
function organizeTokens(list) {
for (i = 0; i < list.length - 1; i++) {
if (list[i].indexFound < list[i + 1].indexFound) {
// do nothing
} else if (list[i].indexFound > list[i + 1].indexFound) {
var tempVal = list[i];
list[i] = list[i + 1];
list[i + 1] = tempVal;
} else {
// should not happen unless we are comparing the same token
}
}
};
既然這樣,當我給它的對象數組這個代碼不進行任何差別。這些元素仍然沒有按照他們應該的順序排列。我以正確的方式接近這個嗎?我錯過了明顯的東西嗎?
編輯:-------------------------------------------- -----------------------
示例輸入:organizTokens([{value:「if」,indexFound:7},{value:「a 」,indexFound:0}])
預期輸出:[{值: 「一個」,indexFound:0},{值: 「如果」,indexFound:7}]
實際輸出:[{值:「if」,indexFound:7},{value:「a」,indexFound:0}]
你試過'Array.prototype.sort'嗎?或者你想自己算法解決這個問題? –
我沒有。我現在檢查文檔。我正在尋找最高效,最理想的最簡單的方法 - 因爲它只是我正在構建的Lexer的巨型機器中的一個小型齒輪。 – Streamer
你能發表一個數據輸入的例子,預期的輸出和你真的得到的輸出嗎? – zer00ne