Home >Web Front-end >JS Tutorial >How Can I Fix the Lack of `Array.prototype.indexOf()` in Older Internet Explorer Versions?

How Can I Fix the Lack of `Array.prototype.indexOf()` in Older Internet Explorer Versions?

DDD
DDDOriginal
2024-12-01 05:31:11741browse

How Can I Fix the Lack of `Array.prototype.indexOf()` in Older Internet Explorer Versions?

Fixing Array.indexOf() for Internet Explorer

While working with JavaScript, you might encounter the absence of Array.prototype.indexOf() in Internet Explorer versions up to IE8. To address this, you can extend its functionality 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;
}

To implement this, you should use the following approach:

if (!Array.prototype.indexOf) {

    // Implement function here

}

The above method is recommended by MDC for compatibility reasons.

It's generally not recommended to use browser detection code like:

if (browser == IE Style Browser) {

     // Implement function here

}

The above is the detailed content of How Can I Fix the Lack of `Array.prototype.indexOf()` in Older Internet Explorer Versions?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn