2

I am using jQuery, and I am having an issue with $.inArray in IE7.

$.inArray([],'test')

In IE7 this returns 0, but in Chrome, it returns -1, like it should.

I've tested this in both jQuery 1.4.4 and 1.5.2, and it's the same.

Why does $.inArray not return the same in different browsers?

EDIT: I just had the arguments backwards, why didn't I notice that? But, why did Chrome give -1, and IE7 give 0?

gen_Eric
  • 223,194
  • 41
  • 299
  • 337

1 Answers1

2

You've got the parameters backwards. The element to look for should come first, followed by the array.

Here's the code (from 1.5.0):

  inArray: function( elem, array ) {
     if ( array.indexOf ) {
       return array.indexOf( elem );
     }

     for ( var i = 0, length = array.length; i < length; i++ ) {
       if ( array[ i ] === elem ) {
         return i;
       }
     }

     return -1;
    },

Now an interesting question is why the string ".indexOf()" returns 0 in IE7 when you pass in an empty array as the target. Somebody might know, but I try pretty hard not to worry about why the broken parts of IE7 are the way they are.

edit — interesting update: it turns out that though the above code is definitely there in the jQuery source, it's later redefined. The above definition is at line 691 in the 1.4.4 source, but then later, at line 855, we see:

if ( indexOf ) {
  jQuery.inArray = function( elem, array ) {
    return indexOf.call( array, elem );
  };
}

There, the naked variable "indexOf" is a stashed reference to "Array.prototype.indexOf". When that's called with ".call()", with a string as the first parameter and an empty array as the second, you get -1 back.

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • Wow, I feel stupid now. I should have noticed that I had the arguments backwards >.< But, still why did IE and Chrome give different answers? – gen_Eric Apr 14 '11 at 15:16
  • 2
    @Rocket I think that the "indexOf" test is coming out `true`, because string objects do have an "indexOf" method. Thus, for whatever reason, IE7 is converting the empty array into something that makes it think the string starts with that value. I *suspect* it's the empty string, and whether the empty string appears at the first position of "test" is an interesting philosophical question :-) – Pointy Apr 14 '11 at 15:18
  • Well that sure is odd. I can't think of why that'd happen, but clearly it does ... – Pointy Apr 14 '11 at 15:25
  • @Pointy: JavaScript converts `[] ` to `''`. Oh, and also I enjoyed [this answer](http://stackoverflow.com/questions/2683466/java-string-indexof-and-empty-strings/2683509#2683509) – gen_Eric Apr 14 '11 at 15:25
  • Ah ha!! It seems that the "inArray" code I posted is not really the one used by the library! I'll update the answer. – Pointy Apr 14 '11 at 15:33
  • @Pointy: Thanks a lot, man. Really should have noticed that I got the arguments wrong =/ – gen_Eric Apr 14 '11 at 15:48