function*(Generator Object)实用的实用程序?

kem*_*ica 5 javascript ecmascript-6

这是一项新技术,是ECMAScript 2015(ES6)标准的一部分.该技术的规范已经完成,但请查看兼容性表,了解各种浏览器的使用情况和实现状态.

函数*声明(函数关键字后跟星号)定义了一个生成器函数,它返回一个Generator对象.

您还可以使用GeneratorFunction构造函数和函数*表达式定义生成器函数.

给出的例子:

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
// ...
Run Code Online (Sandbox Code Playgroud)

MDN功能*

题:

虽然这个例子是可以理解的,但我为什么要在这样的事情上使用它:

var index = 0;
function idMaker(){
  return (index < 2) ? index++: undefined;
}
Run Code Online (Sandbox Code Playgroud)

甚至(回答索引范围评论):

var idMaker = function(){
  this.index = 0;
  this.next = function(){
    var res = (this.index < 3) ? this.index++: undefined;
    return { value: res };
  };
}

var gen = new idMaker();

console.log(gen.next().value);
console.log(gen.next().value);
console.log(gen.next().value);
console.log(gen.next().value);
Run Code Online (Sandbox Code Playgroud)