2

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?

Mike Rifgin
  • 10,409
  • 21
  • 75
  • 111
  • 1
    What do you expect it to return, then? – tckmn May 15 '13 at 12:59
  • 2
    You can't. What you can do however, is push the return value to an array for example. Can you be more specific on what you want to achieve? – stlvc May 15 '13 at 12:59
  • 1
    Depending on your target system, [`yield`](https://developer.mozilla.org/en-US/docs/JavaScript/New_in_JavaScript/1.7#Generators) could be a solution ([so-question](http://stackoverflow.com/questions/2282140/whats-the-yield-keyword-in-javascript)). – Yoshi May 15 '13 at 13:02
  • Return something to _where?_ By definition a function only returns one "thing", though that "thing" may be an array or object that contains multiple values. (Unless `yield` works for your situation.) – nnnnnn May 15 '13 at 13:13

4 Answers4

13

Store it inside an array.

var array = [];
for (var i = 0; i < 100; ++i) {
    array.push(i);
}
Niccolò Campolungo
  • 11,824
  • 4
  • 32
  • 39
5

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.

Patrick D
  • 6,659
  • 3
  • 43
  • 55
2

Store the values you need to return in an array, then after the loop, return the array.

Geeky Guy
  • 9,229
  • 4
  • 42
  • 62
0

There are 3 ways to solve this

  1. 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)
}
  1. 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)
  1. 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();
}
noelyahan
  • 4,195
  • 1
  • 32
  • 27