
有时,开发人员可能需要将函数存储在队列中,并按照存储在队列中的顺序执行它。在JavaScript中,我们可以使用数组来创建一个队列。我们可以使用数组的push()方法将函数入队列,并使用shift()方法从队列中出队函数。
Below, we will see examples of storing JavaScript functions in the queue and executing them in the queue order.
Syntax
用户可以按照以下语法将JavaScript函数存储在队列中,并按顺序执行。
while (queue.length > 0) { queue[0](); queue.shift(); }
我们使用上述语法中的while循环来遍历队列。我们执行队列中的第一个函数,然后将该函数从队列中移除。
立即学习“Java免费学习笔记(深入)”;
Example
在下面的示例中,我们创建了一个名为queue的变量,并用空数组初始化它,使其成为一个队列。
序列猴子开放平台
具有长序列、多模态、单模型、大数据等特点的超大规模语言模型
0 查看详情
After that, we created three different functions and used the push() method of the array to add all functions into the queue. Whenever users press the button, it calls the executeFunctions() function. In the executeFunctions() function, we use the while loop to deque the function from the queue. In every iteration of the loop, we execute the first function from the array and use the array.shift() method to remove the first element from the array.
Using the array to add functions in Queue and execute functions in particular order
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
"; } function function2() { content.innerHTML += "Function 2 executed
"; } function function3() { content.innerHTML += "Function 3 executed
"; } queue.push(function1); queue.push(function2); queue.push(function3);
Example
在下面的示例中,我们创建了一个数组,用作队列,就像第一个示例一样。之后,我们将sum()、sub()、mul()和div()函数添加到队列中。
在executeFunctions()函数中,我们使用for循环按照队列顺序调用所有函数。此外,我们还使用了call()方法从队列中调用函数。
Using the array to add functions in Queue and execute functions in particular order
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 += "
Subtraction of " + a + " and " + b + " is " + (a - b); } function mul() { content.innerHTML += "
Multiplication of " + a + " and " + b + " is " + (a * b); } function div() { content.innerHTML += "
Division of " + a + " and " + b + " is " + (a / b); } queue.push(sum); queue.push(sub); queue.push(mul); queue.push(div);
用户学会了将函数存储在队列中,并按照队列顺序执行它们。在JavaScript中,没有内置的队列数据结构,但我们可以使用数组作为队列。
In the first example, we have used the shift() method to deque the queue. In the second example, we have used the for loop to execute the functions in order.
以上就是如何将JavaScript函数存储在队列中并按顺序执行?的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/539048.html
微信扫一扫
支付宝扫一扫