Home > Web Front-end > JS Tutorial > Why Doesn\'t `Array.indexOf()` Work in IE8, and How Can I Fix It?

Why Doesn\'t `Array.indexOf()` Work in IE8, and How Can I Fix It?

Barbara Streisand
Release: 2024-11-27 06:24:11
Original
957 people have browsed it

Why Doesn't `Array.indexOf()` Work in IE8, and How Can I Fix It?

Troubleshooting Array.indexOf() Issue in IE8

The indexOf() method is widely available in modern browsers for searching elements within arrays. However, it can encounter issues in older versions of Internet Explorer.

An example script that fails in IE8 due to the missing indexOf() is:

function CheckMe() {
    var allowed = new Array('docx','xls','xlsx', 'mp3', 'mp4', '3gp', 'sis', 'sisx', 'mp3', 'wav', 'mid', 'amr', 'jpg', 'gif', 'png', 'jpeg', 'txt', 'pdf', 'doc', 'rtf', 'thm', 'rar', 'zip', 'htm', 'html', 'css', 'swf', 'jar', 'nth', 'aac', 'cab', 'wgz');
    var fileinput=document.getElementById('f');
    var ext = fileinput.value.toLowerCase().split('.');
    if ( allowed.indexOf(ext[1]) == -1) 
    {
        document.getElementById('uploadsec').innerHTML = document.getElementById('uploadsec').innerHTML;
        alert('This file type is not allowed!');
    }
}
Copy after login

Solution for IE8 Compatibility

To resolve this issue in IE8, it's necessary to explicitly define the indexOf() function for the Array object using a polyfill:

if (!Array.prototype.indexOf) {
  Array.prototype.indexOf = function(elt /*, from*/) {
    // Code from MDN or another compatible implementation
  };
}
Copy after login

After implementing this polyfill, the indexOf() method should function as expected in IE8 and other browsers that may lack native support for it.

The above is the detailed content of Why Doesn\'t `Array.indexOf()` Work in IE8, and How Can I Fix It?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template