If you have worked with JavaScript at any length you are aware that Internet Explorer does not implement the ECMAScript function for Array.prototype.indexOf() [including Internet Explorer 8]. It is not a huge problem, because you can extend the functionality on your page with the following code.
Array.prototype.indexOf = function(obj, start) {
for (var i = (start || 0), j = this.length; i < j; i++) {
if (this[i] === obj) { return i; }
}
return -1;
}
When should I implement this?
Should I wrap it on all my pages with the following check, which checks if the prototype function exists and if not, go ahead and extend the Array prototype?
if (!Array.prototype.indexOf) {
// Implement function here
}
Or do browser check and if it is Internet Explorer then just implement it?
//Pseudo-code
if (browser == IE Style Browser) {
// Implement function here
}
it works for me.
Alternatively, you could use the jQuery 1.2 inArray function, which should work across browsers:
The underscore.js library has an indexOf function you can use instead:
I would recommend this to anyone looking for missing functionality:
http://code.google.com/p/ddr-ecma5/
It brings in most of the missing ecma5 functionality to older browers :)
You should check if it's not defined using
if (!Array.prototype.indexOf)
.Also, your implementation of
indexOf
is not correct. You must use===
instead of==
in yourif (this[i] == obj)
statement, otherwise[4,"5"].indexOf(5)
would be 1 according to your implementation, which is incorrect.I recommend you use the implementation on MDC.
This was my implementation. Essentially, add this before any other scripts on the page. i.e. in your master for a global solution for Internet Explorer 8. I also added in the trim function which seems to be used in allot of frameworks.