ES6新特性之Generator函数
生活随笔
收集整理的這篇文章主要介紹了
ES6新特性之Generator函数
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Generator函數
Generator 函數是 ES6 提供的 一種異步編程解決方案,語法行為與傳統函數完全不同 。
Generator函數有兩個特征: 一是 function命令與函數名 之間有一個星號: 二是 函數體內部使用 yield吾句定義不同的內部狀態。
<script>function* hello(){yield "hello";yield "world";yield "abc";return "qq";}let h = hello();// console.log(h.next());// console.log(h.next());// console.log(h.next());// console.log(h.next());for(let v of h){console.log(v);}</script>用法:
<script> function* hello () { yield "hello"; yield "world"; return "done"; } let h = hello(); console.log(h.next()); //{value: "hello", done: false} console.log(h.next()); //{value: "world", done: false} console.log(h.next()); //{value: "done", done: true} console.log(h.next()); //{value: undefined, done: true} </script>可以看到,通過hello()返回的h對象,每調用一次next()方法返回一個對象,該對象包含了value值和done狀態。直到遇到return關鍵字或者函數執行完畢,這個時候返回的狀態為ture,表示已經執行結束了。
for...of循環?
通過for...of可以循環遍歷Generator函數返回的迭代器。
用法:
?
總結
以上是生活随笔為你收集整理的ES6新特性之Generator函数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ES6新特性之class类的基本语法
- 下一篇: ES6新特性之修饰器