Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Crossbrowser "inArray" function (without jQuery)

I wasn't aware of the bad crossbrowser compatibility of array.indexOf() . But now that I am, I need to find a way to achieve the same thing but without using the previous method.

I tried googling for a while, but found no real convincing answers. For now, I am doing it with loops (but this is slow and I am sure there are better ways)

Side Notes:

  • I can't use jQuery or any other libraries/frameworks.
  • It doesn't necessarily need to return the index (a simply true/false will be ok)

I thought it is not necessary to share my code, since you all know how array-loop check looks like (plus it will lower your IQ)

like image 384
mithril333221 Avatar asked Jan 13 '12 20:01

mithril333221


2 Answers

Here is how inArray is implemented in jQuery:

function inArray(elem, array, i) {
    var len;
    if ( array ) {
        if ( array.indexOf ) {
            return array.indexOf.call( array, elem, i );
        }
        len = array.length;
        i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0;
        for ( ; i < len; i++ ) {
            // Skip accessing in sparse arrays
            if ( i in array && array[ i ] === elem ) {
                return i;
            }
        }
    }
    return -1;
}

You can not use jQuery but why not use their implementation? :-)

Best regards!

like image 136
Minko Gechev Avatar answered Sep 28 '22 08:09

Minko Gechev


From MDN:

if (!Array.prototype.indexOf) {  
    Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {  
        "use strict";  
        if (this == null) {  
            throw new TypeError();  
        }  
        var t = Object(this);  
        var len = t.length >>> 0;  
        if (len === 0) {  
            return -1;  
        }  
        var n = 0;  
        if (arguments.length > 0) {  
            n = Number(arguments[1]);  
            if (n != n) { // shortcut for verifying if it's NaN  
                n = 0;  
            } else if (n != 0 && n != Infinity && n != -Infinity) {  
                n = (n > 0 || -1) * Math.floor(Math.abs(n));  
            }  
        }  
        if (n >= len) {  
            return -1;  
        }  
        var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);  
        for (; k < len; k++) {  
            if (k in t && t[k] === searchElement) {  
                return k;  
            }  
        }  
        return -1;  
    }  
}  

This checks if it sees a native implementation, if not implement it.

Notable Quirks:

t.length >>> 0; is an unsigned shift for force this to a positive number

like image 28
Joe Avatar answered Sep 28 '22 06:09

Joe