Within a for loop I can use break
or continue
. For example:
for(var i=0;i<5;i++){
if(i=3){
continue; //I know this is absurd to use continue here but it's only for example
}
}
But, what if I want to use continue
from within a function within a for loop.
For example:
for(var i=0;i<5;i++){
theFunction(i);
}
function theFunction(var x){
if(x==3){
continue;
}
}
I know that this will throw an error. But, is there any way to make it work or do something similar?
Within a for loop I can use break
or continue
. For example:
for(var i=0;i<5;i++){
if(i=3){
continue; //I know this is absurd to use continue here but it's only for example
}
}
But, what if I want to use continue
from within a function within a for loop.
For example:
for(var i=0;i<5;i++){
theFunction(i);
}
function theFunction(var x){
if(x==3){
continue;
}
}
I know that this will throw an error. But, is there any way to make it work or do something similar?
Share Improve this question edited Nov 1, 2017 at 15:21 Martin Adámek 18.4k5 gold badges48 silver badges71 bronze badges asked Nov 1, 2017 at 15:15 camoflage camoflage 1772 gold badges5 silver badges12 bronze badges 1-
1
It is perfectly possible to call the function outside the context of a loop, in which case
continue
would make absolutely no sense. Therefore it is not possible. Thecontinue
must lexically be inside the loop it's controlling. – deceze ♦ Commented Nov 1, 2017 at 15:22
2 Answers
Reset to default 11Use return value of that function and call continue
based on it:
for (var i = 0; i < 5; i++) {
if (theFunction(i)) {
continue;
}
}
function theFunction(x){
if (x == 3) {
return true;
}
return false;
}
Btw in your code you have if(i=3){
, be aware that you need to use ==
or ===
, single equals sign is for assignment.
My solution would be, if putting for loop inside the function is not a big deal
function theFunction(initial, limit, jump) {
for (var i = initial; i < limit ; i++) {
if (i == jump) {
continue;
} else {
console.log(i)
}
}
}