admin管理员组文章数量:1322847
I need entity that return incrementing integer after each call.
For example I have code.
var id = 0; //global variable =(
function foo() {
....
console.log("Your unique ID is " + id++);
....
}
and it works fine. But I want to use generators for this work.
Something like:
function* getId() {
var id = 0;
while (true) {
yield id++;
}
}
function foo() {
....
console.log("Your unique ID is " + getId());
....
}
But result is only empty figure quotes. What i missed? Maybe using generators is a bad idea for this kind of generation?
I need entity that return incrementing integer after each call.
For example I have code.
var id = 0; //global variable =(
function foo() {
....
console.log("Your unique ID is " + id++);
....
}
and it works fine. But I want to use generators for this work.
Something like:
function* getId() {
var id = 0;
while (true) {
yield id++;
}
}
function foo() {
....
console.log("Your unique ID is " + getId());
....
}
But result is only empty figure quotes. What i missed? Maybe using generators is a bad idea for this kind of generation?
Share Improve this question edited May 8, 2016 at 22:38 Bergi 666k161 gold badges1k silver badges1.5k bronze badges asked May 8, 2016 at 21:42 Stepan LoginovStepan Loginov 1,7675 gold badges24 silver badges55 bronze badges3 Answers
Reset to default 9Your getId
is a generator function that creates a generator, instead of advancing one and getting its values.
You should do something like
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());
…
}
Here are the things I can tell are wrong:
- you're resetting the id value on every function call.
- for the generator to output the value of next iteration you need to generate the iterator, then you can access its
next().value
Here's an example:
function* getId() {
var id = 0;
while (true) {
yield id++;
};
}
var itId = getId();
function foo() {
console.log("Your unique ID is " + itId.next().value);
}
foo()
foo()
If you..
- don't want to pollute your namespace
- want short code
Then maybe an IIFE closing over the incremented variable will serve you better than a function*
in this case
var getId = (function () {
var i = 0;
return () => i++;
}());
getId(); // 0
getId(); // 1
getId(); // 2
本文标签: javascriptGet single yield value from iteratorgeneratorStack Overflow
版权声明:本文标题:javascript - Get single yield value from iteratorgenerator - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742113369a2421355.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论