'Using "in" to check whether a string occurs in an array [duplicate]

In Javascript is it possible to check whether a string occurs in an array by using the "in" operator?

For eg:

    var moveAnims   = new Array("fly", "wipe", "flip", "cube");

    alert("wipe" in moveAnims);
    alert("fly " in moveAnims);
    alert("fly" in moveAnims);
    alert("Cube" in moveAnims);

Or is the ONLY way to do it iteratively?

var moveAnims   = new Array("fly", "wipe", "flip", "cube");
var targets     = new Array("wipe", "fly ", "fly", "Cube");

for (var i=0; i<moveAnims.length; i++)
{
    for (var j=0; j<targets.length; j++)
        if (targets[j] == moveAnims[i])
            alert("Found "+targets[j]);
}


Solution 1:[1]

You should be able to use .indexOf() to get the position of the object. Check whether it's -1 to see if it's not there.

Solution 2:[2]

No, because the in operator checks the keys of an object, which in an array are 0, 1, 2, ....

You can use indexOf, however:

if(~moveAnims.indexOf("fly")) { // ~ is a useful hack here (-1 if not found, and
    // ...                      // ~-1 === 0 and is the only falsy result of ~)
}

Note that indexOf isn't available in older browsers, but there are shims out there.

Solution 3:[3]

Try indexOf

moveAnims.indexOf('string')

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tom van der Woerdt
Solution 2 pimvdb
Solution 3 ilija veselica