如何修复Internet Explorer浏览器的JavaScript中的数组indexOf() [英] How to fix Array indexOf() in JavaScript for Internet Explorer browsers

查看:98
本文介绍了如何修复Internet Explorer浏览器的JavaScript中的数组indexOf()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您使用JavaScript的任何时间,您都知道Internet Explorer没有为Array.prototype.indexOf()[包括Internet  Explorer  8]实现ECMAScript函数。这不是一个巨大的问题,因为您可以使用以下代码扩展页面上的功能。

  Array.prototype.indexOf = function(obj,start){
for(var i =(start || 0),j = this.length; i if(this [i] == = obj){return i; }
}
return -1;
}

我应该什么时候实现?



我应该用下面的检查来包装它,它检查原型函数是否存在,如果没有,继续扩展Array原型?

  if(!Array.prototype.indexOf){

//在这里实现函数

}

或者进行浏览器检查,如果是Internet Explorer,那么只需实现它?

  //伪代码

if(browser == IE Style Browser){

//此处实现函数

}


解决方案

...

  if(!Array.prototype.indexOf){

}

As MDC推荐的兼容性



一般来说,浏览器检测代码是一个很大的no-no。 >

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

}

解决方案

Do it like this...

if (!Array.prototype.indexOf) {

}

As recommended compatibility by MDC.

In general, browser detection code is a big no-no.

这篇关于如何修复Internet Explorer浏览器的JavaScript中的数组indexOf()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆