在 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 [ ]