如何在队列中存储 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