簡體   English   中英

Javascript:負循環的用例是什么?

[英]Javascript: What is the use case for negative loops?

我通常使用正數的 for 循環。

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

我很想知道在什么用例中會使用倒數?

這里有一個例子:

當您從數據庫中檢索數據(例如博客文章)時,大多數情況下,數據將是一個包含對象的數組,並通過您網站上的循環呈現它們,最后插入數據庫的數據將顯示在頂部。 也許您想顯示最舊的博文,這樣您就可以將循環更改為倒數。

我希望你明白我的意思,這只是一個例子

假設您有一個包含 10 個數字的數組。

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

您的任務是刪除可被 2 整除的那些並轉換為帶有a the others 的字符串(例如1將是1a )。 (為了論證,假設不存在mapfilter功能)。

如果從一開始就解析數組for (i = 0; i < myArray.length; i++) ,則每次使用例如splice刪除一個項目時,數組長度都會發生變化,並且不會正確解析所有項目。

但是,如果您從頭開始,這將不是問題。

如果您嘗試遍歷任何類似 object 的數組中的項目(使用數組的.length作為循環邊界)並刪除它們,您會發現如果您遞增計數,則循環不會運行正確數量的次,因為每次刪除項目時length都會改變:

 // 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>

但是,如果您刪除集合末尾的元素並向后工作,則length調整不會與集合的內容不同步:

 // 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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM