Home > Web Front-end > JS Tutorial > Why Does `Array.indexOf()` Fail in IE8, and How Can It Be Fixed?

Why Does `Array.indexOf()` Fail in IE8, and How Can It Be Fixed?

DDD
Release: 2024-11-21 00:36:17
Original
898 people have browsed it

Why Does `Array.indexOf()` Fail in IE8, and How Can It Be Fixed?

Array.indexOf() Function Fails in IE8

The indexOf() function, used to check the index of an element in an array, presents challenges in Internet Explorer (IE) versions prior to 9. Specifically, in IE8, this function doesn't work as expected, leaving developers stumped.

To trace the root cause, consider the following function, which is functional in browsers such as Opera, Firefox, and Chrome:

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) {...
Copy after login

The error occurs when the function attempts to execute the if (allowed.indexOf(ext[1]) == -1) conditional statement. In IE8, indexOf() is not supported for arrays, causing the code to fail.

To rectify this issue, the following fix can be implemented:

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;
  };
}
Copy after login

This fix adds the indexOf() method to the Array prototype if it's not present, specifically targeting IE8 or below where it's missing. By incorporating this fix, the CheckMe() function would perform as intended, resolving the issue in IE8.

The above is the detailed content of Why Does `Array.indexOf()` Fail in IE8, and How Can It Be Fixed?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template