IndexOf not Supported in IE8 Browser

余生颓废 提交于 2019-12-01 03:51:36

The indexOf() method of Arrays is not implemented in IE < 9. As you're using jQuery you can make use of the $.inArray(), e.g.

var arr = ["foo", "bar", "baz"],
    bazIndex = $.inArray("baz", arr), // 2
    doesntExistIndex = $.inArray("notThere", arr); // -1

Here's the documentation: http://api.jquery.com/jQuery.inArray/.

The documentation for indexOf on MDN includes a pollyfill that will add support in browsers that don't support JavaScript 1.6.

You can drop it in to avoid having to rewrite the existing code.

if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
        "use strict";
        if (this == null) {
            throw new TypeError();
        }
        var t = Object(this);
        var len = t.length >>> 0;
        if (len === 0) {
            return -1;
        }
        var n = 0;
        if (arguments.length > 0) {
            n = Number(arguments[1]);
            if (n != n) { // shortcut for verifying if it's NaN
                n = 0;
            } else if (n != 0 && n != Infinity && n != -Infinity) {
                n = (n > 0 || -1) * Math.floor(Math.abs(n));
            }
        }
        if (n >= len) {
            return -1;
        }
        var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
        for (; k < len; k++) {
            if (k in t && t[k] === searchElement) {
                return k;
            }
        }
        return -1;
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!