Javascript Operator "in"
Solution 1:
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 1PROPERTY or KEY in your array.
Details here: https://developer.mozilla.org/en/JavaScript/Reference/Operators/in
Solution 2:
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";
Solution 3:
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.
Solution 4:
1 is a valid vanilla numeric array index, x is not; in works with array indexes/object member names, not their values.
Solution 5:
"1" is not a property of the array object...
Post a Comment for "Javascript Operator "in""