1

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]);
}
Andreas Köberle
  • 106,652
  • 57
  • 273
  • 297
sazr
  • 24,984
  • 66
  • 194
  • 362

3 Answers3

2

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.

Tom van der Woerdt
  • 29,532
  • 7
  • 72
  • 105
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.

pimvdb
  • 151,816
  • 78
  • 307
  • 352
  • 1
    The negated result of `-1` is implementation defined though. `-1` **might not** be equal to binary `1111 1111` on all systems. OP should check so that the value is/isn't equal to `-1`, it is guaranteed to work and will ease readability if code is to be passed among several developers. – Filip Roséen - refp Dec 28 '11 at 21:51
  • @refp: Thanks for noting, but I thought the formula is just `~x === -x - 1` as also noted [here](http://en.wikipedia.org/wiki/Bitwise_operation#NOT). And `- -1 - 1 === 0`. – pimvdb Dec 28 '11 at 21:53
  • IIRC the ecma standard doesn't force systems implementing it to use two's-complement, even though it's not common there are other systems to represent negative numbers. OP could (and probably will) be safe using your method, but it isn't 100% guaranteed. – Filip Roséen - refp Dec 28 '11 at 21:58
  • @refp: Thanks for clarifying; I was never aware of that. – pimvdb Dec 28 '11 at 21:59
1

Try indexOf

moveAnims.indexOf('string')
ilija veselica
  • 9,414
  • 39
  • 93
  • 147