Javascript - Loop through array backwards with forEach

前端 未结 7 897
醉梦人生
醉梦人生 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:28

    array.forEach has 3 parameters. You can use these to effectively forEach backward.

    var arr = [1, 2, 3];
    
        arr.forEach(function(x, index, the_array) {
            let x_prime = the_array[the_array.length-1-index]
            console.log(x_prime);
        })
    

    will print

    3
    2
    1
    

提交回复
热议问题