Reputation: 57
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?
Upvotes: 2
Views: 912
Reputation: 28206
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]);
Upvotes: 1
Reputation: 120
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])
}
Upvotes: 1
Reputation: 1278
Please use this code.
var test = [1,2,3,4,5]
test.forEach((val, index) => console.log(test[test.length - index - 1]));
Upvotes: 0
Reputation: 2293
You can reverse()
the array before the loop:
var test = [1,2,3,4,5]
test.reverse().forEach(e => console.log(e));
Upvotes: 2