开发者

$.inArray in IE7

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.

开发者_StackOverflow中文版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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜