2012-06-07 20 views
1

的結果時的性能正如您可能已知的,indexOf的返回值是index(找到)或-1(未找到)。比較indexOf

有許多方法來測試這個結果,其中一些是:

if (result != -1) //different than -1 
if (result >= 0) //greater or equal to 0 

與其他不常用的選項:

if (result + 1) //-1 turns to: -1 + 1 = 0 (falsish value) 
if (~result) //-1 turns to: -(-1 + 1) = 0 (falsish value) 

和無數的其他選項...

哪種方法在所有瀏覽器中表現良好?

+0

相關(關於最佳實踐)http://stackoverflow.com/questions/10175818/best-practice-for-testing-return-value-of-indexof – ajax333221

回答

3

我跑了一些intensive tests前一陣子,我比所有這些組合:

if (~results) 
if (results > -1) 
if (!(results < 0)) 
if (results >= 0) 
if (!(results <= -1)) 
if (results != -1) 
if (!(results == -1)) 
if (results + 1) 
if (!(results + 1)) 

my tests,我每次添加兩條線,一條用一個成功的結果,一個失敗。原因是因爲我們希望這兩種情景的平均值能夠更好地瞭解它通常如何執行。

我的結論是,~xx >= 0是非常好的選擇,但我會選擇後者,因爲可讀性和代碼維護性更容易。

0

如果你關心性能,你可以考慮製作自己的indexOf方法。看看這個performance test,結果令我感到驚訝。另請注意,IE8及以下版本不支持indexOf