Does JavaScript array.forEach traverse elements in ascending order

前端 未结 3 447
陌清茗
陌清茗 2020-12-29 19:48

In JavaScript I can have an array with holes:

a = [];
a[0] = 100;
a[5] = 200;
a[3] = 300;

a.forEach(function(x) {alert(x);});

I could not

3条回答
  •  一向
    一向 (楼主)
    2020-12-29 20:19

    Straight out of the ECMAScript standard

    forEach calls callbackfn once for each element present in the array, in ascending order. callbackfn is called only for elements of the array which actually exist; it is not called for missing elements of the array.

    So Array.forEach will skip certain elements in an array. Your example

    a.forEach( function( value ) { console.log( value ) }); // prints 100, 300, 200
    

    If you do want to traverse the array in ascending order and all your elements are numbers then you can sort the array beforehand like so

    a.sort( function( a, b ) { return a - b });
    // this now prints 100, 200, 300
    a.forEach( function( value ) { console.log( value ) }); 
    

提交回复
热议问题