js generator資料類型

來源:互聯網
上載者:User

標籤:

1. 概述

   generator 是ES6引入的新的資料類型, 看上去像一個函數,除了使用return返回, yield可以返回多次。

   generator 由function* 定義, (注意*號),

2. 例子

  函數無法儲存狀態, 有時需要全域變數來儲存數字;

  2.1

‘use strict‘;function next_id(){   var id = 1;   while(id<100){      yield id;      id++;   }   return id;}// 測試:var    x,    pass = true,    g = next_id();for (x = 1; x < 100; x ++) {    if (g.next().value !== x) {        pass = false;        alert(‘測試失敗!‘);        break;    }

}
if (pass) { alert(‘測試通過!‘);}

   2.2 一個無限迴圈的迭代器

 

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

 

2.3Generator.prototype.next()

當迭代結束時, Generator.next().done ===true, 結束之前 ===false

function* gen() {   yield 1;  yield 2;  yield 3;}var g = gen(); // "Generator { }"g.next();      // "Object { value: 1, done: false }"g.next();      // "Object { value: 2, done: false }"g.next();      // "Object { value: 3, done: false }"g.next();      // "Object { value: undefined, done: true }"

 

2.4 Generator.prototype.return();

return方法 返回給定的參數值,並結束迭代器

example

function* gen() {   yield 1;  yield 2;  yield 3;}var g = gen();g.next();        // { value: 1, done: false }g.return("foo"); // { value: "foo", done: true }g.next();        // { value: undefined, done: true }

注意 如果 done的值是true了, 再調用return,返回的值也是undefined

function* gen() {yield 1;}var g = gen();console.log(g.next());//{ value: 1, done: false }console.log(g.next());//{ value: undefined, done: true }console.log(g.return(1)); //{ value: undefined, done: true }

 

2.5 Generator.prototype.throw()

  thorw()方法, 通過拋出一個異常到迭代器中,來重新獲得迭代器的執行;

   返回 帶有 value和done兩個屬性的object對象

function* gen() {  while(true) {    try {       yield 42;    } catch(e) {      console.log("Error caught!");    }  }}var g = gen();var a = g.next();// { value: 42, done: false }var b = g.throw(new Error("Something went wrong"));// "Error caught!"// { value: 42, done: false }console.log(a);console.log(b.value+"::"+b.done);

 

  

 

js generator資料類型

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.