JavaScript 中的生成器函数是什么?
生成器函数允许在函数退出而在之后恢复时在函数内部执行代码。因此,可以使用生成器函数来管理代码中的流控制。由于可以随时暂停执行,从而可以轻松取消异步操作。
以下是语法;不要忘记在“function”关键字后加上星号。你可以使用以下任意一种方式添加星号 −
function *myFunction() {}
// or
function* myFunction() {}
// or
function*myFunction() {}示例
让我们看看如何使用生成器函数
<html>
<body>
<script>
function* display() {
var num = 1;
while (num < 5)
yield num++;
}
var myGenerator = display();
document.write(myGenerator.next().value);
document.write("<br>"+myGenerator.next().value);
document.write("<br>"+myGenerator.next().value);
document.write("<br>"+myGenerator.next().value);
document.write("<br>"+myGenerator.next().value);
</script>
</body>
</html>
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP