tags:

views:

245

answers:

3

Excerpt from my JavaScript console:

> 0 in [1, 2]
true

Why?

+19  A: 

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.

Adam Wright
Further to this, Felix is probably looking for `indexOf`: https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Array/indexOf (which requires JS 1.6, but that URI includes an implementation you can include in your code for browsers still on 1.5 or earlier)
David Dorward
+2  A: 

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;
    }
}
PatrikAkerstrand
+4  A: 

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
egon