Home >Web Front-end >JS Tutorial >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!'); } }
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 }; }
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!