Coder Perfect

Why doesn’t indexOf work on an array in Internet Explorer 8?


Opera, Firefox, and Chrome all support the feature below. However, in Internet Explorer 8, it fails on the if (allowed) condition. part indexOf(ext[1]) == -1)

Is there a reason for this? Is there anything that stands out as a mistake?

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!');

Asked by nLL

Solution #1

Before trying to use the.indexOf() function for Array in versions of Internet Explorer prior to IE9, perform this to determine the exact standard version:

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;

This is the MDN version that Firefox/SpiderMonkey uses. In other circumstances, such as Internet Explorer, it will add. indexOf() in the case it’s missing… basically IE8 or below at this point.

Answered by Nick Craver

Solution #2

You can use $.inArray() instead if you’re using jQuery.

Answered by tiegz

Solution #3

If you’re using jQuery and don’t want to worry about compatibility issues, you can do the following:

if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function(val) {
        return jQuery.inArray(val, this);

When you want to keep utilizing indexOf but have a fallback in case it isn’t available, this is useful.

Answered by Mehdiway

Solution #4

For a really thorough explanation and workaround, not only for indexOf but other array functions missing in IE check out the StackOverflow question Fixing JavaScript Array functions in Internet Explorer (indexOf, forEach, etc.)

Answered by Luis Perez

Solution #5

If you’re going to utilize $.inArray, be cautious. I recently discovered that $.inArray only works with “Array” and not with String. As a result, this function will not operate in Internet Explorer 8!

The jQuery API causes a lot of confusion.

–> “Similar” should not be used. Because indexOf also supports “String”!

Answered by ptgamr

Post is based on