JavaScript indexOf vs Array.prototype.indexOf IE兼容性错误 [英] JavaScript indexOf vs Array.prototype.indexOf IE compatibility error
问题描述
可能重复:
为什么indexOf不能在IE8阵列上工作?
我最近开发了一个使用原生Javascript和jQuery的脚本。我的大部分开发都是使用IE 9,Chrome,Firefox。对于所有这些,下面的行完美地运作:
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)
然而今天我将一些代码推送到生产系统并且有几个客户来了回来说他们的网页坏了。我已将搜索范围缩小到 indexOf
,显然IE 8并不是最不喜欢的。所以我试图找到一个替代方案,我发现这个位 Array.prototype.indexOf
但是我不确定如何把它绑成一个if-else类似于上面。
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.
此外,如果有更好的选择,那么我全都是耳朵。另外,这是我可能只需要应用于IE 8浏览器的东西,如果找到IE 8,使用它,如果不使用原始的?
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?
推荐答案
这个问题多次出现,可以在这里找到另一个Stackoverflow线程:如何在JavaScript中为Internet Explorer浏览器修复数组indexOf()
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
几个人在不同的主题建议使用 this来自MDC的代码。这似乎是代码:
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;
};
}
在进行任何调用之前只需运行此代码indexOf()
Just run this code before making any calls indexOf()
这篇关于JavaScript indexOf vs Array.prototype.indexOf IE兼容性错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!