javascript - .indexOf() 在 IE8 中不工作

标签 javascript jquery internet-explorer-8

<分区>

我为其中一个工作平台创建了这个小交互 - http://jsfiddle.net/S79qp/427/

它在除 IE8 之外的所有浏览器中都能正常工作。当我运行控制台时,似乎是这部分出现问题...

index = a.indexOf(current) + 1;
if (index < 0 ||  index >= l.length) {
    index = 0;
}

谁能告诉我一个 IE8 友好的替代品,这样我就可以让它与所需的版本兼容?

最佳答案

当您查看 MDN 的 Array.indexOf 时文章,你会看到的

indexOf is a recent addition to the ECMA-262 standard; as such it may not be present in all browsers. You can work around this by utilizing the following code at the beginning of your scripts. This will allow you to use indexOf when there is still no native support. This algorithm matches the one specified in ECMA-262, 5th edition, assuming Object, TypeError, Number, Math.floor, Math.abs, and Math.max have their original values.

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 > 1) {
            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;
    }
}

关于javascript - .indexOf() 在 IE8 中不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16187428/

相关文章:

javascript - 是否可以从 JavaScript 调用 hamlet?

javascript - 加速 Angular $compile 函数

javascript - 在一个容器中我有文本和 img 标签,我怎样才能只用 js 或 jquery 获取文本

javascript - jQuery超时改变内容

javascript - 设置脚本元素的 innerHTML 在 IE8 上不起作用

javascript - DOM 加载后,Jquery 函数无法与多个函数一起使用

javascript - JS 在 `display: none` 和 `display: flex` 之间切换

jquery - 如何避免 Web 应用程序框架冲突

css - IE8 在导入 CSS 时不会渲染背景图片

javascript - 强制 IE8 在 margin-left 后重绘/重绘