如何在佇列中儲存 JavaScript 函式並按順序執行?
有時,開發者可能需要將函式儲存在佇列中,並按其在佇列中的儲存順序執行。在 JavaScript 中,我們可以使用陣列建立一個佇列。我們可以使用陣列的 push() 方法將函式入隊,使用 shift() 方法將函數出隊。
下面,我們將看到一些在佇列中儲存 JavaScript 函式並在佇列順序中執行它們的示例。
語法
使用者可以按照以下語法在佇列中儲存 JavaScript 函式並按順序執行。
while (queue.length > 0) {
queue[0]();
queue.shift();
}
我們在上面的語法中使用 while 迴圈來迭代佇列。我們執行佇列中的第一個函式,然後從佇列中移除該函式。
示例
在下面的示例中,我們建立了佇列變數並將其初始化為空陣列以使其成為佇列。
之後,我們建立了三個不同的函式,並使用陣列的 push() 方法將所有函式新增到佇列中。每當使用者按下按鈕時,它都會呼叫 executeFunctions() 函式。在 executeFunctions() 函式中,我們使用 while 迴圈將函式從佇列中出隊。在迴圈的每次迭代中,我們執行陣列中的第一個函式,並使用 array.shift() 方法從陣列中移除第一個元素。
<html>
<body>
<h3>Using the array to add functions in Queue and execute functions in particular order</h3>
<div id = "content"> </div></br>
<button onclick = "executeFunctions()"> Execute function in queue order </button>
<script>
let content = document.getElementById("content");
// execute the functions in the order they are added to the queue
var queue = [];
function executeFunctions() {
while (queue.length > 0) {
queue[0]();
queue.shift();
}
}
function function1() {
content.innerHTML += "Function 1 executed <br>";
}
function function2() {
content.innerHTML += "Function 2 executed <br>";
}
function function3() {
content.innerHTML += "Function 3 executed <br>";
}
queue.push(function1);
queue.push(function2);
queue.push(function3);
</script>
</body>
</html>
示例
在下面的示例中,我們建立了像第一個示例一樣的用作佇列的陣列。之後,我們將 sum()、sub()、mul() 和 div() 函式新增到佇列中。
在 executeFunctions() 函式中,我們使用 for 迴圈按佇列順序呼叫所有函式。此外,我們還使用了 call() 方法來呼叫佇列中的函式。
<html>
<body>
<h3>Using the array to add functions in Queue and execute functions in particular order</h3>
<div id = "content"> </div> </br>
<button onclick = "executeFunctions()"> Execute function in queue order </button>
<script>
let content = document.getElementById("content");
// execute the functions in the order they are added to the queue
var queue = [];
function executeFunctions() {
for (let i = 0; i < queue.length; i++) {
queue[i].call();
}
}
let a = 10;
let b = 5;
function sum() {
content.innerHTML += "Sum of " + a + " and " + b + " is " + (a + b);
}
function sub() {
content.innerHTML += "<br>Subtraction of " + a + " and " + b + " is " + (a - b);
}
function mul() {
content.innerHTML += "<br>Multiplication of " + a + " and " + b + " is " + (a * b);
}
function div() {
content.innerHTML += "<br>Division of " + a + " and " + b + " is " + (a / b);
}
queue.push(sum);
queue.push(sub);
queue.push(mul);
queue.push(div);
</script>
</body>
</html>
使用者學習瞭如何在佇列中儲存函式並按佇列順序執行它們。在 JavaScript 中,沒有內建的佇列資料結構,但我們可以使用陣列作為佇列。
在第一個示例中,我們使用了 shift() 方法將隊列出隊。在第二個示例中,我們使用了 for 迴圈按順序執行函式。
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP