I have a for loop that needs to return something on every iteration:
for(var i=0;i<100;++i) {
return i;
}
but return breaks the loop. How can I return but kee the loop running?
asked May 15, 2013 at 12:57
Mike Rifgin
10.9k22 gold badges78 silver badges115 bronze badges
4 Answers 4
Store it inside an array.
var array = [];
for (var i = 0; i < 100; ++i) {
array.push(i);
}
answered May 15, 2013 at 12:59
Niccolò Campolungo
12k4 gold badges35 silver badges40 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
Geeky Guy
@Doorknob This is not Java.
Mike Rifgin
thought as much. I can't use an array in this instance.
tckmn
@MikeRifgin Then what do you want it to return?
The context here is unclear. If you are trying to execute a function for each iteration of the loop, why not something simple like calling a function from within the loop?
for(var i=0;i<100;++i) {
processIteration(i)
}
In processIteration you could simply handle what you need to happen with that value.
answered May 15, 2013 at 13:00
Patrick D
6,8493 gold badges47 silver badges55 bronze badges
Comments
Store the values you need to return in an array, then after the loop, return the array.
answered May 15, 2013 at 12:59
Geeky Guy
9,3895 gold badges46 silver badges65 bronze badges
Comments
There are 3 ways to solve this
- Promises
function loop() {
promises = []
for (var i = 0; i < 100; ++i) {
// push a promise resolve to a promises array
promises[i] = Promise.resolve(i);
}
return promises;
}
// Observe the promises loop
for (let p of loop()) {
p.then(console.log)
}
- Callbacks
function loop(cb) {
for(var i = 0; i < 100; ++i) {
// calling the callback
cb(i);
}
}
// Pass a do something method
// Here it's the console log as the callback
loop(console.log)
- Yield
// Generator function for loop over 100
function* loop() {
for (var i = 0; i < 100; ++i) {
// return value from loop
yield i;
}
}
// Initialize the generator function
let it = loop();
// Call and get the resulr
// it.next().value
var result = it.next();
while (!result.done) {
console.log(result.value); // 1 2 3 .... 99
result = it.next();
}
answered Aug 15, 2018 at 5:42
noelyahan
4,2751 gold badge34 silver badges28 bronze badges
Comments
lang-js
yieldcould be a solution (so-question).yieldworks for your situation.)