【JavaScript】ES6 新文法

來源:互聯網
上載者:User

標籤:屬性   環境   ref   asc   cti   title   tps   pre   strong   

function* 聲明

function* 聲明(function關鍵字後跟一個星號)定義一個generator(產生器)函數,返回一個Generator對象。

產生器是一種可以從中退出並在之後重新進入的函數。產生器的環境(綁定的變數)會在每次執行後被儲存,下次進入時可繼續使用。

調用一個產生器函數並不馬上執行它的主體,而是返回一個這個產生器函數的迭代器(iterator)對象。當這個迭代器的next()方法被調用時,產生器函數的主體會被執行直至第一個yield運算式,該運算式定義了迭代器返回的值,或者,被 yield*委派至另一個產生器函數。next()方法返回一個對象,該對象有一個value屬性,表示產出的值,和一個done屬性,表示產生器是否已經產出了它最後的值。

yield

function* idMaker(){  var index = 0;  while(index<3)    yield index++;}var gen = idMaker();console.log(gen.next().value); // 0console.log(gen.next().value); // 1console.log(gen.next().value); // 2console.log(gen.next().value); // undefined

yield*

function* anotherGenerator(i) {  yield i + 1;  yield i + 2;  yield i + 3;}function* generator(i){  yield i;  yield* anotherGenerator(i);  yield i + 10;}var gen = generator(10);console.log(gen.next().value); // 10console.log(gen.next().value); // 11console.log(gen.next().value); // 12console.log(gen.next().value); // 13console.log(gen.next().value); // 20

  

【JavaScript】ES6 新文法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.