日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

ES6新特性之Generator函数

發(fā)布時(shí)間:2024/4/13 编程问答 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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ù)返回的迭代器。
用法:

<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>

?

總結(jié)

以上是生活随笔為你收集整理的ES6新特性之Generator函数的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。