最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

JavaScript 'continue' within if statement - Stack Overflow

programmeradmin3浏览0评论

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. The continue must lexically be inside the loop it's controlling. – deceze Commented Nov 1, 2017 at 15:22
Add a ment  | 

2 Answers 2

Reset to default 11

Use 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)
        }
    }
}
发布评论

评论列表(0)

  1. 暂无评论