1

Possible Duplicate:
javascript in operator

Why does ("a" in ["a","b"]) yield false, and (1 in [1,2]) yield true ? Is there a reason why "a" does not match the first element of that array and 1 does ? Why won't it work with strings ?

Community
  • 1
  • 1
João Pinto Jerónimo
  • 9,586
  • 15
  • 62
  • 86

1 Answers1

5

The in operator checks for the existence of properties by key, not by value. And your array of length 2 has an index "1" - arr["1"] is the value 2. For example, also 0 in ["a", "b"] is true. The behaviour does not depend on a string or a number being used.

You usually would use it on plain objects, not on arrays. Like "a" in {a:1} === true, or "b" in {a:1} === false.

pimvdb
  • 151,816
  • 78
  • 307
  • 352
Bergi
  • 630,263
  • 148
  • 957
  • 1,375