Javascript 为什么 indexOf 在数组 IE8 上不起作用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3629183/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 05:29:05  来源:igfitidea点击:

Why doesn't indexOf work on an array IE8?

javascriptinternet-explorerinternet-explorer-8indexof

提问by nLL

The below function works fine on Opera, Firefox and Chrome. However, in IE8 it fails on the if ( allowed.indexOf(ext[1]) == -1)part.

下面的函数在 Opera、Firefox 和 Chrome 上运行良好。但是,在 IE8 中它失败了if ( allowed.indexOf(ext[1]) == -1)

Does anyone know why? Is there any obvious 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!');
    }
}

回答by Nick Craver

Versions of IE before IE9 don't have an .indexOf()function for Array, to define the exact spec version, run this before trying to use it:

IE9 之前的 IE 版本没有.indexOf()用于 Array的函数,要定义确切的规范版本,请在尝试使用它之前运行它:

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 version from MDN, used in Firefox/SpiderMonkey. In other cases such as IE, it'll add .indexOf()in the case it's missing... basically IE8 or below at this point.

这是来自 MDN的版本,用于 Firefox/SpiderMonkey。在其他情况下,例如 IE,它会.indexOf()在丢失的情况下添加......此时基本上是 IE8 或更低版本。

回答by tiegz

If you're using jQuery, you can use $.inArray()instead.

如果您使用 jQuery,则可以使用$.inArray()代替。

回答by Mehdiway

If you're using jQueryand want to keep using indexOf without worrying about compatibility issues, you can do this :

如果您正在使用jQuery并希望继续使用 indexOf 而不必担心兼容性问题,您可以这样做:

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

This is helpful when you want to keep using indexOfbut provide a fallback when it's not available.

当您想继续使用indexOf但在不可用时提供后备时,这很有用。

回答by Luis Perez

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.)

要获得真正彻底的解释和解决方法,不仅对于 indexOf,而且对于 IE 中缺少的其他数组函数,请查看 StackOverflow 问题Fixing JavaScript Array functions in Internet Explorer(indexOf、forEach 等)

回答by ptgamr

Please careful with $.inArray if you want to use it. I just found out that the $.inArray is only works with "Array", not with String. That's why this function will not working in IE8!

如果你想使用它,请小心使用 $.inArray。我刚刚发现 $.inArray 仅适用于“Array”,而不适用于 String。这就是为什么这个功能在 IE8 中不起作用的原因!

The jQuery API make confusion

jQuery API 造成混淆

The $.inArray() method is similar to JavaScript's native .indexOf() method in that it returns -1 when it doesn't find a match. If the first element within the array matches value, $.inArray() returns 0

$.inArray() 方法类似于 JavaScript 的原生 .indexOf() 方法,因为它在找不到匹配项时返回 -1。如果数组中的第一个元素与值匹配,则 $.inArray() 返回 0

--> They shouldn't say it "Similar". Since indexOf support "String" also!

--> 他们不应该说“相似”。由于 indexOf 也支持“String”!

回答by John Slegers

The problem

问题

IE<=8 simply doesn't have an indexOf()method for arrays.

IE<=8 根本没有indexOf()数组的方法。



The solution

解决方案

If you need indexOfin IE<=8, you should consider using the following polyfill, which is recommended at the MDN:

如果您indexOf在 IE<=8 中需要,您应该考虑使用以下polyfill,这是MDN 推荐的

if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function(searchElement, fromIndex) {
        var k;
        if (this == null) {
            throw new TypeError('"this" is null or not defined');
        }
        var o = Object(this);
        var len = o.length >>> 0;
        if (len === 0) {
            return -1;
        }
        var n = +fromIndex || 0;
        if (Math.abs(n) === Infinity) {
            n = 0;
        }
        if (n >= len) {
            return -1;
        }
        k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
        while (k < len) {
            if (k in o && o[k] === searchElement) {
                return k;
            }
            k++;
        }
        return -1;
    };
}

Minified :

缩小:

Array.prototype.indexOf||(Array.prototype.indexOf=function(r,t){var n;if(null==this)throw new TypeError('"this" is null or not defined');var e=Object(this),i=e.length>>>0;if(0===i)return-1;var a=+t||0;if(Math.abs(a)===1/0&&(a=0),a>=i)return-1;for(n=Math.max(a>=0?a:i-Math.abs(a),0);i>n;){if(n in e&&e[n]===r)return n;n++}return-1});

回答by Robert Cadmire

You can use this to replace the function if it doesn't exist:

如果该函数不存在,您可以使用它来替换该函数:

<script>
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;
    };
}
</script>