2013-04-09 60 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方法找到一个跨浏览器实现。

相关问题