简体   繁体   中英

Javascript: What is the use case for negative loops?

I normally use for loops which count positively.

var i;
for (i = 0; i < cars.length; i++) {
  text += cars[i] + "<br>";
}

I am curious to know in what use case would counting backwards be used?

Here a example:

When you retrieve data from a database for example blogposts, the data will be most of the time an array with objects in it and render them via a loop on your website the last data that was inserted in the database will be display at the top. Maybe you want to show the oldest blogpost so you could just change your loop to count backwards.

I hope you get the point what I mean, that's just a example

Say you have an array of 10 numbers.

const myArray = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

Your task is to delete the ones that are divisible by 2 and convert to a string with an a the others (for example 1 will be 1a ). (For the sake of the argument let´s say no map or filter functions exist).

If you parse the array from the start for (i = 0; i < myArray.length; i++) , everytime you delete an item with for example splice the array length changes and no all items will be correctly parsed.

BUT if you starts from the end this will be not a problem.

If you were attempting to loop over items in any array-like object (using the .length of the array as your loop boundary) and delete them, you'd find that if you counted incrementally, the loop would not run the correct amount of times because the length would change each time you deleted an item:

 // Get all the divs into a collection let divs = document.getElementsByTagName("div"); // Set up a loop that will go as many times as there are items in the collection for(var i = 0; i < divs.length; i++){ divs[i].remove(); // Remove the div being iterated from the page }
 <div>One</div> <div>Two</div> <div>Three</div> <div>Four</div> <div>Five</div>

But, if you remove the elements at the end of the collection and work backwards, the length is adjustment doesn't get out of sync with the contents of the collection:

 // Get all the divs into a collection let divs = document.getElementsByTagName("div"); // Set up a loop that will go as many times as there are items in the collection // But count backwards to keep the length from causing issues. for(var i = divs.length - 1; i > -1; i--){ divs[i].remove(); // Remove the div being iterated from the page }
 <div>One</div> <div>Two</div> <div>Three</div> <div>Four</div> <div>Five</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM