Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
158 views
in Technique[技术] by (71.8m points)

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

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].

(如果您曾经使用过JavaScript,那么您就会知道Internet Explorer不会为Array.prototype.indexOf()[包括Internet Explorer 8]实现ECMAScript函数。)

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?

(我是否应该使用以下检查将其包装在我的所有页面上,该检查将检查原型函数是否存在,如果不存在,请继续并扩展Array原型?)

if (!Array.prototype.indexOf) {

    // Implement function here

}

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

(还是要检查浏览器,如果它是Internet Explorer,则只需实施它?)

//Pseudo-code

if (browser == IE Style Browser) {

     // Implement function here

}
  ask by Bobby Borszich translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Do it like this...

(像这样做...)

if (!Array.prototype.indexOf) {

}

As recommended compatibility by MDC .

(如MDC建议的兼容性 。)

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

(通常,浏览器检测代码是很大的禁忌。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...