How to count downwards with forEach loop javascript

Viewed 367

So I want to go through an list of objects but I cant index it but can use forEach to go through the elements... My problem is I need to go from the last Object to the first but dont know how to do that with the forEach function! If i'd do a for loop it would look something like this:

var test = [1,2,3,4,5]
   for (let i = test.length; i > -1; i=i-1) {
       console.log(test[i])
   }

But as I explained I somehow cant index it. So can you help me?

4 Answers

You can reverse() the array before the loop:

var test = [1,2,3,4,5]
 
test.reverse().forEach(e => console.log(e));

Here is the code for your problem:

var test = [1, 2, 3, 4, 5]
    for (let i = test.length - 1; i >= 0; i--) {
      console.log(test[i])
    } 

This is a variant of Severin.Hersche's approach:

const test = [1, 2, 3, 4, 5];
for (let i = test.length;i--;) console.log(test[i]);

Please use this code.

var test = [1,2,3,4,5]
test.forEach((val, index) => console.log(test[test.length - index - 1]));

Related