1

I'm used to python, so

a = [1,2,3]
1 in a # -> True
b = ["1", "2", "3", "x"]
"x" in b # -> True

Why is it that in JavaScript

a = [1,2,3]
1 in a // -> true
b = ["1", "2", "3", "x"]
"x" in b // -> false

and much weirder

"1" in b // -> true
Ruggero Turra
  • 16,929
  • 16
  • 85
  • 141
  • Might be a duplicate of http://stackoverflow.com/questions/237104/array-containsobj-in-javascript – scurker Mar 09 '12 at 14:47

5 Answers5

2

in works on KEYS of arrays, not values. 1 in a succeeds because there is an element #1 in your array, which is actually the 2 value.

"1" fails, because there is no 1 PROPERTY or KEY in your array.

Details here: https://developer.mozilla.org/en/JavaScript/Reference/Operators/in

Marc B
  • 356,200
  • 43
  • 426
  • 500
  • There's [array.indexOf](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf), but it's a newer JS feature and won't be in older implementations. – Marc B Mar 09 '12 at 14:58
1

The thing you have to understand about JavaScript is almost everything is an "Object" that can have properties. Array's are just a special type of object whose properties are integer indexes and have push, pop, shift, unshift, etc. methods. Plus they can be defined with the square bracket shorthand you used:

a = [1,2,3];

This creates an Array object with the properties:

a[0] = 1;
a[1] = 2;
a[2] = 3;

Now as others have said, all the in operator does is check that an object has a property of that name and a[1] == 2 therefore 1 in a == true. On the other hand,

b = ["1", "2", "3", "x"];

created an Array object with the properties:

b[0] = "1";
b[1] = "2";
b[2] = "3";
b[3] = "x";

So b["x"] == undefined therefore "x" in b == false.

The other thing you have to understand is JavaScript uses "duck typing", meaning if it looks like a number, JavaScript treats it like a number. In this case, b["1"] == 2 therefore "1" in b == true. I'm not 100% certain whether this is duck typing at work or JavaScript just always treats property names as Strings.

If you wanted to declare a generic object that wouldn't have the Array methods but had the same properties you would write:

var b = {"0": "1", "1": "2", "2": "3", "3": "x"};

Which is shorthand for:

var b = {}; // This declares an Object
b[0] = "1";
b[1] = "2";
b[2] = "3";
b[3] = "x";
nwellcome
  • 2,279
  • 15
  • 23
0

Because "x" in b is looking for a property name 'x'. There is none, they are all numerical (but still string) property names, considering it is an array.

alex
  • 479,566
  • 201
  • 878
  • 984
0

1 is a valid vanilla numeric array index, x is not; in works with array indexes/object member names, not their values.

Alex K.
  • 171,639
  • 30
  • 264
  • 288
0

"1" is not a property of the array object...

Alex
  • 34,899
  • 5
  • 77
  • 90