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
"1" is not a property of the array object...
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.
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
1
is a valid vanilla numeric array index, x
is not; in
works with array indexes/object member names, not their values.
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";