Javascript - Loop through array backwards with forEach

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

    No, forEach only processes forward through the array. So you'd have to do something else, which you've said in your question was out of scope.

    I can think of two options which just use precursors to using forEach (so, they don't use a for loop or other kind of loop). I don't know if those would be out of scope or not, so here they are:

    1. Copy the array and reverse the copy, then use forEach on it

    2. Use Object.keys to get the indexes, reverse that, then use forEach on it (which will loop through the indexes, not the values, but then we can look them up)

    Here's #1:

    slice copies the array (shallow copy, so not likely to be expensive), then we reverse it, then forEach:

    var a = ['one', 'two', 'three'];
    a.slice().reverse().forEach(function(entry) {
        console.log(entry);
    });
    console.log("Proof that a is not, itself, reversed: " +
                JSON.stringify(a));

    Here's #2:

    We use Object.keys to get the array indices (using filter if you store non-element properties in your arrays), reverse that, and then loop through the result:

    var a = ['one', 'two', 'three'];
    Object.keys(a).reverse().forEach(function(index) {
        console.log(a[index]);
    });
    console.log("Proof that a is not, itself, reversed: " +
                JSON.stringify(a));


    Side note: Here's what I mean about using filter if you have non-element properties on your array:

    var a = ['one', 'two', 'three'];
    a.nonElementProperty = "foo";
    Object.keys(a).filter(function(name) {
      return String(+name) === name;
    }).reverse().forEach(function(index) {
        console.log(a[index]);
    });
    console.log("Proof that a is not, itself, reversed: " +
                JSON.stringify(a));

    0 讨论(0)
提交回复
热议问题