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?
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?
Store it inside an array.
var array = [];
for (var i = 0; i < 100; ++i) {
array.push(i);
}
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.
Store the values you need to return in an array, then after the loop, return the array.
There are 3 ways to solve this
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)
}
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)
// 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();
}