JavaScript indexOf vs Array.prototype.indexOf IE compatibility error
Possible Duplicate:
Why doesn't indexOf work on an array IE8?
I recently developed a script that uses native Javascript and jQuery. Most of my development has been with IE 9, Chrome, Firefox. For all of them the line below works perfectly:
if(data.cols.indexOf("footprint") < 0)
However today I pushed a bit of my code to a production system and a couple of the clients have come back saying their pages are broken. I have narrowed my search down to indexOf
, which apparently IE 8 does not like in the slightest. So I am trying to find an alternative and I found this bit Array.prototype.indexOf
but I am not really sure how I would tie that into an if-else similar to above.
Also if there is a better alternative then I am all ears. Also, is this something I may have to apply to IE 8 browsers only, where if IE 8 is found, use this, if not use the original?
This question has come up many times, another Stackoverflow thread can be found here: How to fix Array indexOf() in JavaScript for Internet Explorer browsers
Several people on different threads have recommended using this code from MDC. This appears to be the code:
if (!Array.prototype.indexOf)
{
Array.prototype.indexOf = function(elt /*, from*/)
{
var len = this.length >>> 0;
var from = Number(arguments[1]) || 0;
from = (from < 0)
? Math.ceil(from)
: Math.floor(from);
if (from < 0)
from += len;
for (; from < len; from++)
{
if (from in this &&
this[from] === elt)
return from;
}
return -1;
};
}
Just run this code before making any calls indexOf()
链接地址: http://www.djcxy.com/p/18954.html上一篇: IE8 Javascript问题