JavaScript >> Javascript 文檔 >  >> JavaScript

在 JavaScript 中實現隊列數據結構 [示例]

一個隊列 是一種常用的數據結構 在編程中。下面介紹如何在 JavaScript 中實現和使用隊列。

JavaScript 不包含專門稱為隊列的數據結構 – 但這並不意味著功能不存在。

JavaScript 數組可以以相同的方式使用——只是術語有點不同。 隊列功能存在於 JavaScript 的數組函數中,而不是複制隊列的數組功能。

什麼是隊列數據結構?

一個隊列 是按特定順序排列的項目序列。項目可以排隊 (添加到隊列中)或出列 (從隊列中移除)。

項目被添加到隊列的前面,當它們完成時,從隊列的後面移除。這稱為先進先出 (FIFO )。

如果你曾經在超市的收銀台前排隊——那就是排隊。顧客在付款時加入隊列(入隊)並離開商店,並在付款後離開隊列(出隊)。 編程中的隊列的工作方式完全相同 - 將項目添加到隊列中,並在您希望對其執行的任何任務完成後將其刪除。

JavaScript 數組作為隊列

JavaScript 數組可以創建很棒的隊列——所需的功能就在那裡;它只是作為 Array 對象的一部分,而不是作為單獨的 Queue 對象。

代碼對話——這裡是一個使用 JavaScript 數組實現的隊列:

定義隊列

下面,使用一個空數組來初始化隊列:

var petsQueue = [];// Create an empty array to act as a queue

將項目添加到隊列(入隊)

push() 可以在數組上使用方法將項目添加到隊列中:

petsQueue.push('dog'); // Adds 'dog' to the queue
petsQueue.push('cat'); // Adds 'cat' to the queue
petsQueue.push('bird'); // Adds 'bird' to the queue

查看隊列內容

您可以使用 console.log() 將隊列的內容輸出到控制台 :

console.log(petsQueue) // [ "dog", "cat", "bird" ]

從隊列中移除項目(出隊)

當從隊列中刪除一個項目時,我們會想要對它做一些事情。下面,從隊列中刪除一個項目並存儲在一個新變量中以供使用:

var nextPet = petsQueue.shift(); // The queue is now ['cat', 'bird']
console.log(nextPet);            // displays 'dog'

您現在可以對 nextPet 執行操作 ,完成後,轉到隊列中的下一項。

您可以在隊列中存儲任何類型的對像或變量——可以添加和刪除代表任務或人員的對像以進行處理。

完整示例 – 使用 JavaScript 數組作為隊列

下面,定義了一個隊列,添加了一些項目,然後使用 while 循環處理隊列,直到它被清空:

var petsQueue = [];// Create an empty array to act as a queue

petsQueue.push('dog'); // Adds 'dog' to the queue
petsQueue.push('cat'); // Adds 'cat' to the queue
petsQueue.push('bird'); // Adds 'bird' to the queue

console.log(petsQueue) // Check the contents of the queue - [ "dog", "cat", "bird" ]

// Loop through the queue until it is empty (when it's length is zero)
while (petsQueue.length > 0) {
    var nextPet = petsQueue.shift(); // Dequeue the next pet and assign them to a variable
    console.log(nextPet + ' has been washed!');// Do something with the item taken from the queue
}   

console.log(petsQueue) // Confirm that the queue was fully processed - it is now empty with the value [ ]


Tutorial JavaScript 教程
  1. 關於 jQuery 方法的 5 個鮮為人知的細節

  2. 和''在JavaScript中有不同的含義嗎?

  3. Showdev:我們正在構建一個在線會議應用程序 - Collabify 🎉🎦🖼🎭

  4. 如何將 React API 數據轉換為 props 以在其他組件中使用?

  5. 第 0 天 - Dynastorm 的誕生

  6. 為什麼回調地獄有效而 async/await 無效? (在我正在測試的這種特殊情況下)

  7. 概念證明 - 動態過濾大量選擇

  1. 使用 Object Literals - [en-US] 替換您的 switch 語句和多個 if 和 else。

  2. 用 window.addEventListener 隱藏 div 不起作用

  3. 如何在 Safari/Chrome 中從 javascript 打印 IFrame

  4. 添加事件監聽器的最佳實踐(javascript、html)

  5. QnA 系統

  6. 突破現代瀏覽器的極限

  7. 當我在另一個工作表上處於活動狀態時隱藏一個工作表

  1. JavaScript Array 對象未打印到控制台

  2. 我的第一個 Vue npm 包

  3. 最大事件數問題

  4. 嘗試故事書驅動的開發