这是一项新技术,是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
// ...
问题:
虽然这个例子是可以理解的,但我为什么要使用它呢?
var index = 0;
function idMaker(){
return (index < 2) ? index++: undefined;
}
或甚至(回答索引范围注释):
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);