Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript string in list returns false

Tags:

javascript

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 ?

like image 939
Nix Avatar asked Oct 25 '25 12:10

Nix


2 Answers

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.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/indexOf

like image 58
Bart Avatar answered Oct 28 '25 03:10

Bart


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)

like image 28
Denys Séguret Avatar answered Oct 28 '25 04:10

Denys Séguret