I'm parsing an array using $.each()
, but inside it, I'm using .splice()
method, so I need to iterate backward. Is it possible ?
var store = [...];
//...
var rules = [...];
//...
$.each(store, function(index, element) { // This loop needs to iterate backward
$.each(rules, function(index2, rule) {
if (element.id == rule.id) {
store.splice(index, 1);
}
});
});
WARN :
for
, I just want to know if it's achievable using $.each
You cannot iterate backwards with the jQuery each function, but you can still leverage jQuery syntax. //get an array of the matching DOM elements var liItems = $ ("ul#myUL li").get (); //iterate through this array in reverse order for (var i = liItems.length - 1; i >= 0; --i) { //do Something }
I found Array.prototype.reverse unsuccessful with objects, so I made a new jQuery function to use as an alternative: jQuery.eachBack (). It iterates through as the normal jQuery.each () would, and stores each key into an array. It then reverses that array and performs the callback on the original array/object in the order of the reversed keys.
Iterating over jQuery and non-jQuery Objects. jQuery provides an object iterator utility called $.each() as well as a jQuery collection iterator: .each(). These are not interchangeable. In addition, there are a couple of helpful methods called $.map() and .map() that can shortcut one of our common iteration use cases.
The $.each() function is not the same as $(selector).each(), which is used to iterate, exclusively, over a jQuery object. The $.each() function can be used to iterate over any collection, whether it is an object or an array. In the case of an array, the callback is passed an array index and a corresponding array value each time.
$.each(store.reverse(), function(index, element) { // This loop iterate backward
[...]
This works, it's the same as this post jquery-each-backwards. But the point here is, you're applying this over the store
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With