JavaScript 中的生成器函数是什么?
javascriptweb developmentfront end technology
生成器函数允许在函数退出和稍后恢复之间执行代码。因此,生成器可用于管理代码中的流控制。由于可以随时暂停执行,因此可以轻松取消异步操作。
以下是语法;不要忘记在"function"关键字后添加星号。您可以使用以下任何减号添加星号
function *myFunction() {}
// 或
function* myFunction() {}
// 或
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>
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

