Given the code
var loops = 5;
var counter = 0;
function foo(counts){
var baz = 0;
for(var i=0;i<loops;i++){
baz += i + counts;
}
return baz;
}
for(var i=0;i<foo(counter);i++){ //issue in this line
console.log(i);
}
Every time that the for loop increments, it calls the foo function again.
Why is it doing this and is there a way to prevent this?
I understand that I can just store the return in a variable, but I'm still rather curious why this happens.
It doesn't happen in other languages like python.
The way I tested that it does this is by setting a breakpoint in the foo function.
The stop condition is evaluate each iteration. If you want to evaluate only once do that:
var loops = 5; var counter = 0; function foo(counts){ var baz = 0; for(var i=0;i<loops;i++){ baz += i + counts; } return baz; } for(var i=0,l=foo(counter);i<l;i++){ //issue in this line console.log(i); }
The equivalent python code would be
i = 0
while i < foo(counter):
print(i)
i++
That's just what a for
loop does, the condition is evaluated before every iteration. If you want to call foo
only once, you have to explicitly cache the result in a variable:
for (var i=0, n=foo(counter); i<n; i++) {
console.log(i);
}
The (more pythonic) alternative would be to use an range
generator (which is not available in the JS standard library though), where foo
is called only once to create the iterator:
for (var i of range(0, foo(counter)) {
console.log(i);
}
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.