$.each()
itself cannot be iterated backwards as there is no modifier for it. The input it takes is from a selector. which can be converted into an array. Then $.each()
iterates forwards by index (0,1,2,... and so on).
The only way to reverse flow is to either Array.reverse()
or find an iterator loop that does so. You can also build a recursion function that serves your purpose. But all these options are outside the limitation of $.each()
Here are options from iteration loops to consider:
-> for loop (reverse)
var value = 10;
for (var i = value; i; i--){
console.log(i);
//bonus
//return back to a proper flow is to add the whole value it
console.log(value + i);
}
-> while loop (reverse):
var X=9,Y=X;
while (--Y) {
console.log(Y);
//will only stop at 1 since while cannot return a falsy value
//0 is considered a falsy value, and is nullified from the loop
}
Options to consider to reverse array iteration:
-> Array.reverse().forEach()
As my late mentor once said, There is more than one way to carve an elephant from stone.
This site exists because many people have creative ways to solve issues. Unfortunately, there isn't anything built into $.each()
that will run backwards stand-alone, hence people resorting to other means (some of which are mentioned above). Im sorry this isnt a satisfactory "yes" answer to the question, but hopefully explains why $.each()
can only loop forward. If this is me making my own solution it would be this:
var loopy=(value,output)=>{
for(var i = value; i; i--){
output.call(this,{
index:{
forward:()=>value-i,
reverse:()=>i-1
},
count:{
forward:()=>1+value-1,
reverse:()=>i
}
})
}
}
loopy(10, i=>console.log( i.index.forward() ))
The function above allows you to have options ranging whole counts and index counts. This is similar to how Array.forEach()
works except youre outputting an object and its values per iteration. I use a function similar to this to fetch object's values, keys, and indexes.
.reverse()
on the array. Please, fully read the question. – Somnolent.splice
, you have to iterate backward. And$.each()
isn't basically. – Somnolentfor
loop? – Scarrow$.each()
. – Somnolent