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 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)
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!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With