I've tried but every time I get a different weird output. Ideally, it should print 0, 1, 2, 3, 4 and come out of the loop but it doesn't happen.
function foo(iteration) {
if (iteration === 5) {
return;
}
for (let i = 0; i < 5; i++) {
console.log(i);
foo(iteration + 1);
}
}
foo(0);
To understand the current output, start by walking through your function step by step. It helps me to write it out and keep track of the values.
iteration
starts at 0
it starts the for loop
i
is 0
at this point.
its logged to the console.
foo
is called again with value of 1
iteration
is still less than 5
a new for loop starts. (step 2)
i
is 0
, this is a brand new loop since it's inside of a new instance of foo
In each iteration of the for loop, you call foo
and while iteration
is less than 5
you start a new for loop.
Here is an example of a function that does what you like:
function foo(iteration) { while(iteration < 5) { console.log(iteration) iteration++ } } foo(0)
You don't need to use recursion AND a loop. Just the loop itself will work.
for (let i = 0; i < 5; i++) { console.log(i); }
Or, just recursion:
function foo(i) { if (i >= 5) return true; console.log(i); foo(i + 1); } foo(0);
What you're doing is saying: While foo-iteration is less than 5, console.log five times and start up FIVE NEW incremented foo-iterations. Each of those 5 new foo-iterations will console.log five times on their own and start up FIVE NEW incremented foo-iterations, and so on until the foo-iterations finally reach 5. Do you see how this tailspins out of control?
Since you are already using recursion, there is no need to have that loop. Something like this should work:
function foo(iteration) { if (iteration < 5) { console.log(iteration); foo(iteration + 1); } } foo(0)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.