So i'd like to make a function that sequentially generates a number each execution, I was wondering how to do this in Javascript I need this to basically set an order to my items in mongoDB. How can I write a JS function that generates a number sequentially each time it's run? ex: 1... then run the function again...2 then again...3.
Asked
Active
Viewed 358 times
-3
-
http://stackoverflow.com/questions/2282140/whats-the-yield-keyword-in-javascript – Delgan Jul 18 '15 at 22:34
-
`yield` is still (too) rare in JavaScript implementations. – Kuba Wyrostek Jul 18 '15 at 22:36
-
The "sad" thing here is that the [tag:mongodb] tag in the question leads me to believe you actually wanted this: [Create an Auto-Incrementing Sequence Field](http://docs.mongodb.org/manual/tutorial/create-an-auto-incrementing-field/), yet just got "owned" for lack of research and asking more in terms of a [tag:javascript] question than explaining what you were going to use it for. – Blakes Seven Jul 19 '15 at 02:37
-
@BlakesSeven how did I get owned? – user3649245 Jul 19 '15 at 18:43
1 Answers
2
var next = (function() {
var v = 0;
return function() {
return v++;
}})();
console.log(next()); // 0
console.log(next()); // 1
console.log(next()); // 2

Kuba Wyrostek
- 6,163
- 1
- 22
- 40