Home >Web Front-end >JS Tutorial >Why Doesn\'t indexOf Work Correctly with Arrays in IE8?
indexOf Function Anomaly in IE8 for Array Objects
The provided JavaScript function, designed to validate file extensions, encounters an issue specifically in IE8 during the execution of the if ( allowed.indexOf(ext[1]) == -1) statement. This failure prompts the question of why the indexOf function is not executing correctly in IE8.
The indexOf function, a native method in JavaScript arrays, returns the index of the first occurrence of a specified element within the array. However, in pre-IE9 versions of Internet Explorer, this function was not defined for arrays. As a result, attempting to utilize indexOf on an array in IE8 triggers the error.
Solution
To address this discrepancy, a polyfill can be employed before utilizing the indexOf function. A polyfill is a code snippet that grants compatibility with older browser versions. In this instance, the polyfill for Array.prototype.indexOf can be implemented as follows:
if (!Array.prototype.indexOf) { Array.prototype.indexOf = function(elt, from) { var len = this.length >>> 0; var from = Number(arguments[1]) || 0; from = (from < 0) ? Math.ceil(from) : Math.floor(from); if (from < 0) from += len; for (; from < len; from++) { if (from in this && this[from] === elt) return from; } return -1; }; }
Implementing this polyfill ensures that the indexOf function is available in older IE versions, allowing the JavaScript function to operate as intended.
The above is the detailed content of Why Doesn\'t indexOf Work Correctly with Arrays in IE8?. For more information, please follow other related articles on the PHP Chinese website!