JavaScript:Internet Explorer 不支持 forEach 方法。

9

我正在使用JavaScript实现的gzip算法,它在Firefox和Chrome上运行良好。但是,在Internet Explorer中我遇到了以下错误:

不支持forEach方法!

代码:

deflate.deflate(data, level).forEach(function (byte) {
    putByte(byte, out);
});

我正在使用支持forEach方法的Internet Explorer 9浏览器。

有什么建议吗?

非常感谢!


1
forEach在IE8中不受支持。然而,IE9应该支持它。http://kangax.github.io/es5-compat-table/#Array.prototype.forEach - James Donnelly
2
你的页面在IE中是否以怪异模式运行?(可能是意外吗?).forEach()仅在标准模式下受支持。deflate.deflate()是否总是返回一个数组? - nnnnnn
与其扩展内置对象,您可以用两行 for 循环替换 forEach 部分。 - RobG
2个回答

23

你可以尝试扩展Array对象,以便在不支持其forEach方法的浏览器中使用,如此处建议的Array.forEach

一个例子是:

if (!Array.prototype.forEach) {
    Array.prototype.forEach = function(fn, scope) {
        for(var i = 0, len = this.length; i < len; ++i) {
            fn.call(scope, this[i], i, this);
        }
    }
}

0

在IE9中不支持forEach,您可以尝试使用jQuery。
例如:

$. each (function (byte) {
  putByte(byte, out);
});

4
我希望您避免使用jQuery。 - Alexander Schreiber
我使用了jQuery作为解决方法,并对结果感到满意。$.eachdata.Emails, function( index, value ) { $('#lblEmails').append(value + " "); }); - jon.r
为了实现一个for循环而添加整个库并增加页面加载时间是不好的。 - Marcos Lima

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接