Javascript ForEach函数在IE中不起作用

时间:2013-02-12 07:18:52

标签: javascript jquery function internet-explorer-8 foreach

我怎么能写下以下所有浏览器都支持的代码? 因为似乎IE8中不支持forEach-Function ...

    digits.forEach( function( value, index ) {
    // create a span with initial conditions
    var span = $( '<span>', {
        'class': 'digit0',
        'data': {
            'current': 0,
            'goal' : value
        }
    } );
    // append span to the div#number
    span.appendTo( $( 'div#number' ) );
    // call countUp after interval multiplied by the index of this span
    setTimeout( function() { countUp.call( span ); }, index * interval );
} );

请参阅此处的完整代码http://jsfiddle.net/bBadM/(不适用于所有浏览器) 提前谢谢。

此致

1 个答案:

答案 0 :(得分:10)

MDN documentation for forEach包括在实现早期版本的JS的浏览器中使用的方法的两种实现。

我会在这里重现快速的(请参阅完整的链接):

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