Javascript - Loop through array backwards with forEach

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

    Just use a for loop. Start at the end of the array and go backwards from there.

    const array = ['blastoff', 1, 2, 3];
    
    for (let index = array.length - 1; index >= 0; index--) {
      const element = array[index];
      console.log(element);
    }

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-03 17:15

    let arr = [1, 2, 3];
    
    arr.slice().reverse().forEach(x => console.log(x))

    will print:

    3
    2
    1
    

    arr will still be [1, 2, 3], the .slice() creates a shallow copy.

    0 讨论(0)
  • 2020-12-03 17:26

    This can be accomplished relatively concisely using the reverse method, the forEach method, and (if using ES6) the arrow function

    var someArray = ["a","b","c","d"];
    someArray.reverse().forEach(arrayItem =>
        console.log(arrayItem)
    )
    

    If you are not using ES6, the solution is about the same, just without the arrow function.

    var someArray = ["a","b","c","d"];
    someArray.reverse().forEach(function(arrayItem) {
        console.log(arrayItem)
    })
    

    Both will print to the console:

    d
    c    
    b
    a
    
    0 讨论(0)
  • 2020-12-03 17:26

    As yet the browsers do not seem to have optimised the Array.forEach function. With not much effort you can write a simple polyfill that out performs the Array.forEach method by at least 10 to 1.

    So you can create your own Array.revEach and have it outperform the native Array.forEach, thought I hope that the browsers address the very slow performance of Array.forEach soon and make the need to polyfill actual existing methods not necessary.

    For Array.revEach out performs Array.forEach running 17 times faster on "Chrome 46.0.2490.22 beta-m"

    if (Array.prototype.revEach === undefined) { 
        Object.defineProperty(Array.prototype, 'revEach', { 
            writable : false,
            enumerable : false,
            configurable : false,
            value : function (func) {
                var i;
                var len = this.length-1;
                for (i = len; i >= 0; i--) {
                    func(this[i], i, this);
                }
            }
        });
    }
    

    Just to add the actual official polyfill modified to reverse. Comments show my changes.

    // Production steps of ECMA-262, Edition 5, 15.4.4.18
    // Reference: http://es5.github.io/#x15.4.4.18
    // Modified by Blindman67 to revEach
    if (!Array.prototype.revEach) {   // name changed
      Array.prototype.revEach = function(callback, thisArg) { // name changed
        var T;  // k defined where len was
        if (this == null) {
          throw new TypeError(' this is null or not defined');
        }
        var O = Object(this);
        var k = (O.length >>> 0)-1;  // set k (counter) ToUint32
                                     // len var removed
        if (typeof callback !== "function") {
          throw new TypeError(callback + ' is not a function');
        }
        if (arguments.length > 1) {
          T = thisArg;
        }
        while (k >= 0) {  // reverse condition
          var kValue;
          if (k in O) {
            kValue = O[k];
            callback.call(T, kValue, k, O);
          }
          k--;  // dec counter
        }
      };
    }
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题