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

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

问题描述

如果您使用过 JavaScript,您就会知道 Internet Explorer 没有为 Array.prototype.indexOf() [包括 Internet Explorer 8] 实现 ECMAScript 函数.这不是什么大问题,因为您可以使用以下代码扩展页面上的功能.

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;
}

我应该什么时候实施?

我是否应该通过以下检查将其包装在所有页面上,检查原型函数是否存在,如果不存在,则继续扩展数组原型?

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

}

或者做浏览器检查,如果它是 Internet Explorer 那么就执行它?

Or do browser check and if it is Internet Explorer then just implement it?

//Pseudo-code

if (browser == IE Style Browser) {

     // Implement function here

}

推荐答案

这样做...

if (!Array.prototype.indexOf) {

}

作为 MDC 推荐的兼容性.

一般来说,浏览器检测代码是一个很大的禁忌.

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

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

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