Excerpt from m开发者_JAVA技巧y JavaScript console:
> 0 in [1, 2]
true
Why?
Because "in" returns true if the specified property/index is available in the object. [1, 2] is an array, and has a object at the 0 index. Hence, 0 in [1, 2], and 1 in [1, 2]. But !(2 in [1, 2]).
Edit: For what you probably intended, David Dorward's comment below is very useful. If you (somewhat perversely) want to stick with 'in', you could use an object literal
x = {1: true, 2: true};
This should allow 1 in x && 2 in x && !(0 in x)
etc. But really, just use indexOf.
Because there is a 0
-th element in the array.
> 0 in [8,9]
true
> 1 in [8,9]
true
> 8 in [8,9]
false
You are probably looking for [1,2].indexOf(0)
. indexOf
might not work in ie6 though.
Here is one implementation that fixes it:
if(!Array.indexOf) {
Array.prototype.indexOf = function(obj) {
for(var i=0; i<this.length; i++) {
if (this[i]==obj) {
return i;
}
}
return -1;
}
}
精彩评论