Ste*_*nov 2 javascript generator node.js ecmascript-6
我需要在每次调用后返回递增整数的实体.
例如,我有代码.
var id = 0; //global variable =(
function foo() {
....
console.log("Your unique ID is " + id++);
....
}
Run Code Online (Sandbox Code Playgroud)
它工作正常.但我想使用发电机来完成这项工作.
就像是:
function* getId() {
var id = 0;
while (true) {
yield id++;
}
}
function foo() {
....
console.log("Your unique ID is " + getId());
....
}
Run Code Online (Sandbox Code Playgroud)
但结果只是空图引号.我错过了什么?也许使用发电机对于这类发电来说是一个坏主意?
你getId是一个生成器函数,它创建一个生成器,而不是推进它并获得它的值.
你应该做点什么
function* IdGenerator() {
var i = 0;
while (true) {
yield i++;
}
}
IdGenerator.prototype.get = function() {
return this.next().value;
};
var ids = IdGenerator();
function foo() {
…
console.log("Your unique ID is " + ids.get());
…
}
Run Code Online (Sandbox Code Playgroud)