详解JavaScript的生成器函数(function*)

一、生成器函数是什么?

function * 定义的函数称之为生成器函数,返回值是一个 Generator 对象,不能直接使用,需要通过调用 next() 方法来使用。

1、语法
// 语法
function* name([param[, param[, ... param]]]) { statements }
2、简单实例
// 实例
function* generator(i) {
	return  i+1;
}
const gen = generator(10);
console.log(gen.next());
// 输出:{value: 11, done: true}
3、不能作为构造函数
function* f() {}
var obj = new f; // throws "TypeError: f is not a constructor"
二、其他特性
1、yield

yield 关键字可以让生成器函数变成异步函数。yield 作用是暂停运行代码,直至下一次 next() 方法被调用。

function* generator(i) {
    yield i;
    yield i + 10;
}
const gen = generator(10);

console.log(gen.next().value);
// 输出: 10
console.log(gen.next().value);
// 输出: 20
2、yield*

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); // 10
console.log(gen.next().value); // 11
console.log(gen.next().value); // 12
console.log(gen.next().value); // 13
console.log(gen.next().value); // 20
3、return

return 表示无需等待,直接返回。

function* yieldAndReturn() {
  yield "Y";
  return "R";//显式返回处,可以观察到 done 也立即变为了 true
  yield "unreachable";// 不会被执行了
}

var gen = yieldAndReturn()
console.log(gen.next()); // { value: "Y", done: false }
console.log(gen.next()); // { value: "R", done: true }
console.log(gen.next()); // { value: undefined, done: true }
三、更多使用场景
1、完整调用
function* idMaker(){
  var index = 0;
  while(index<3)
    yield index++;
}

var gen = idMaker();
console.log(gen.next().value); // 0
console.log(gen.next().value); // 1
console.log(gen.next().value); // 2
console.log(gen.next().value); // undefined
2、构造时传递参数
// 可以接受参数
function* idMaker(){
    var index = arguments[0] || 0;
    while(true)
        yield index++;
}

var gen = idMaker(5);
console.log(gen.next().value); // 5
console.log(gen.next().value); // 6
3、运行时传递参数
// 传递参数
function *createIterator() {
    let first = yield 1;
    let second = yield first + 2; // 4 + 2
                                  // first =4 是next(4)将参数赋给上一条的
    yield second + 3;             // 5 + 3
}

let iterator = createIterator();

console.log(iterator.next());    // "{ value: 1, done: false }"
console.log(iterator.next(4));   // "{ value: 6, done: false }"
console.log(iterator.next(5));   // "{ value: 8, done: false }"
console.log(iterator.next());    // "{ value: undefined, done: true }"
4、遍历
// 二维数组变成一维数组
function* iterArr(arr) {            //迭代器返回一个迭代器对象
  if (Array.isArray(arr)) {         // 内节点
      for(let i=0; i < arr.length; i++) {
          yield* iterArr(arr[i]);   // (*)递归
      }
  } else {                          // 离开
      yield arr;
  }
}
// 使用 for-of 遍历:
var arr = ['a', ['b', 'c'], ['d', 'e']];
for(var x of iterArr(arr)) {
        console.log(x);               // a  b  c  d  e
 }

// 或者直接将迭代器展开:
var arr = [ 'a', ['b',[ 'c', ['d', 'e']]]];
var gen = iterArr(arr);
arr = [...gen];                        // ["a", "b", "c", "d", "e"]
四、另外两种生成器函数
1、生成器函数表达式

生成器函数表达式 可以省略函数名,而生成器函数不可以。

// 语法
function* [name]([param1[, param2[, ..., paramN]]]) {
   statements
}
// 实例
const foo = function*() {
  yield 'a';
  yield 'b';
  yield 'c';
};

let str = '';
for (const val of foo()) {
  str = str + val;
}

console.log(str);
// expected output: "abc"
2、GeneratorFunction
  • GeneratorFunction 并不是一个全局对象,只能通过 Object.getPrototypeOf(function*(){}).constructor 创建;
  • 在JavaScript中,生成器函数实际上都是 GeneratorFunction 的实例对象;
  • GeneratorFunction 创建的生成器函数 效率低于 function* 定义的生成器函数,且只能使用本地变量和全部变量。
// 语法
new GeneratorFunction ([arg1[, arg2[, ...argN]],] functionBody)
// 实例
var GeneratorFunction = Object.getPrototypeOf(function*(){}).constructor
var g = new GeneratorFunction("a", "yield a * 2");
var iterator = g(10);
console.log(iterator.next().value); // 20
五、参考文档

相关文章

kindeditor4.x代码高亮功能默认使用的是prettify插件,prett...
这一篇我将介绍如何让kindeditor4.x整合SyntaxHighlighter代...
js如何实现弹出form提交表单?(图文+视频)
js怎么获取复选框选中的值
js如何实现倒计时跳转页面
如何用js控制图片放大缩小