ES6新特性之Generator函数
生活随笔
收集整理的這篇文章主要介紹了
ES6新特性之Generator函数
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
Generator函數(shù)
Generator 函數(shù)是 ES6 提供的 一種異步編程解決方案,語法行為與傳統(tǒng)函數(shù)完全不同 。
Generator函數(shù)有兩個(gè)特征: 一是 function命令與函數(shù)名 之間有一個(gè)星號: 二是 函數(shù)體內(nèi)部使用 yield吾句定義不同的內(nèi)部狀態(tài)。
<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對象,每調(diào)用一次next()方法返回一個(gè)對象,該對象包含了value值和done狀態(tài)。直到遇到return關(guān)鍵字或者函數(shù)執(zhí)行完畢,這個(gè)時(shí)候返回的狀態(tài)為ture,表示已經(jīng)執(zhí)行結(jié)束了。
for...of循環(huán)?
通過for...of可以循環(huán)遍歷Generator函數(shù)返回的迭代器。
用法:
?
總結(jié)
以上是生活随笔為你收集整理的ES6新特性之Generator函数的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ES6新特性之class类的基本语法
- 下一篇: ES6新特性之修饰器