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>

更新於:2020 年 6 月 16 日

224 次瀏覽

開啟你的 職業生涯

完成課程認證

開始
廣告