Javascript - Loop through array backwards with forEach

前端 未结 7 882
醉梦人生
醉梦人生 2020-12-03 17:07

Is there a way to loop backwards through an array using forEach (not any other kind of loop, I know how to do with with a for / standard ways) and without actua

7条回答
  •  醉酒成梦
    2020-12-03 17:13

    There is a similar array method that has a reverse counter part, reduce comes together with reduceRight:

    const array = ['alpha', 'beta', 'gamma'];
    
    array.reduceRight((_, elem) => console.log(elem), null);

    When using it for the requested purpose, make sure to provide a second argument. It can be null or anything else. Also note that the callback function has as first argument the accumulator, which you don't need for this purpose.

    If including a library is an option:

    Lodash: forEachRight.

提交回复
热议问题