javascript string in list returns false - Stack Overflow

My site just started returning false for the following javascript check.I am trying to understand why

My site just started returning false for the following javascript check. I am trying to understand why.

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

Can someone help me understand why ?

My site just started returning false for the following javascript check. I am trying to understand why.

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

Can someone help me understand why ?

Share Improve this question asked Apr 9, 2013 at 20:58 NixNix 58.7k31 gold badges153 silver badges205 bronze badges 1
  • possible duplicate of Javascript - check array for value – Nix Commented Apr 9, 2013 at 21:05
Add a ment  | 

3 Answers 3

Reset to default 8

the in operator tests if a property is in an object. For example

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

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

You want to test if an array contains a specific object. You should use the Array#indexOf method.

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

Array#indexOf at MDN: https://developer.mozilla/en-US/docs/JavaScript/Reference/Global_Objects/Array/indexOf

From the MDN :

The in operator returns true if the specified property is in the specified object.

It checks the key, not the value.

There, the property key would be 0, not "0e52a313167fecc07c9507fcf7257f79".

You can test that 0 in _test is true.

If you want to check if a value is in an array, use indexOf :

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

(a shim given by the MDN is necessary for IE8)

"in" operator searches in object keys, not values. You will have to use indexOf and take care of its non implentation in previous IE versions. So you may find a cross browser implementation for the Array.prototype.indexOf method on the first google result.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745224794a4617410.html

相关推荐

  • javascript string in list returns false - Stack Overflow

    My site just started returning false for the following javascript check.I am trying to understand why

    5小时前
    10

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信