2010-04-25 23 views
0

考慮下面的代碼的一個巨大的數組:如何更好地遍歷,有很多不確定的項目

var _test1 = []; 
_test1[88] = 'sex'; 
_test1[1999990] = 'hey'; 
for(i = 0, length = _test1.length; i < length; i++){ 
    if(_test1[i] == 'hey'){ 
     alert(_test1.length); 
    } 
} 

這需要大量的時間,而且只有2個值。 有什麼辦法可以加快速度嗎?即使通過使用另一個通過數字索引對象然後循環它們的系統?

回答

1

您是否嘗試過使用對象?數字應自動轉換爲字符串。你將遍歷一個for ... in循環的列表。

+0

您不需要切換到對象。 – SLaks 2010-04-25 19:59:21

+0

是的。我認爲這是最好的選擇。比數組重要得多嗎? – 2010-04-25 20:01:19

+0

數組是對象。 – SLaks 2010-04-25 20:05:00

3

您可以使用for/in循環:

for (var i in _test1) { 
    if (!_test1.hasOwnProperty(i) || isNaN(+i)) continue; 

    if(_test1[i] == 'hey'){ 
     alert(_test1.length); 
    } 
} 

這正是你要尋找的;它只會遍歷實際定義的索引,並會跳過數組中的任何空洞。

+0

感謝這個解決方案,我稍後會進行基準測試:D – 2010-04-25 20:22:12