Javascript ForEach Function does not work in IE

2019-07-20 21:41发布

问题:

how could I write the following Code that it is supported in all browsers? Because it seems that the forEach-Function is not supported in IE8...

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

See the full Code here: http://jsfiddle.net/bBadM/ (it´s not working with all browsers) Thanks in advance.

Regards,

回答1:

The MDN documentation for forEach includes two implementations of the method for use in browsers that implement earlier versions of JS.

I'll reproduce the quick one (see the link for the complete one) here:

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