2013-04-09 59 views
2

我的網站剛開始爲下面的JavaScript檢查返回false。我試圖理解爲什麼。JavaScript字符串列表返回false

_test = ["0e52a313167fecc07c9507fcf7257f79"] 
"0e52a313167fecc07c9507fcf7257f79" in _test 
>>> false 
_test[0] === "0e52a313167fecc07c9507fcf7257f79" 
>>> true 

有人可以幫我理解爲什麼嗎?

+0

可能重複的[Javascript - 檢查數組的價值](http://stackoverflow.com/questions/11015469/javascript-check-array-for-value) – Nix 2013-04-09 21:05:23

回答

3

in運營商的測試,如果屬性是在一個對象。例如

var test = { 
    a: 1, 
    b: 2 
}; 

"a" in test == true; 
"c" in test == false; 

你想測試一個數組包含的特定對象。你應該使用Array#indexOf方法。在MDN

test.indexOf("0e52...") != -1 // -1 means "not found", anything else simply indicates the index of the object in the array. 

陣列#的indexOf:https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/indexOf

1

the MDN

的操作中,如果指定的屬性在 指定的對象返回true。

它檢查的重點,而不是價值。

在那裏,房產密鑰將是0,而不是"0e52a313167fecc07c9507fcf7257f79"

您可以測試0 in _testtrue

如果你想檢查一個值是一個數組,使用indexOf

_test.indexOf("0e52a313167fecc07c9507fcf7257f79")!==-1 

(由MDN給出一個墊片是IE8必要)

0

「中的」 在對象鍵操作者的搜索,而不是值。您將不得不使用indexOf並在之前的IE版本中處理其未實現的情況。因此,您可能會在第一個google結果中爲Array.prototype.indexOf方法找到一個跨瀏覽器實現。

相關問題