简体   繁体   English

带有嵌套if的其他语句

[英]Else statement with nested if

Am I correct in assuming that when the first if statement and nested if within the else statement both fail, I then go back up to the first for loop and increment i by 1? 我是否假设第一个if语句和else语句内的嵌套if都失败了,然后回到第一个for循环并将i递增1时是否正确?

So I can continue until j < totalCols fails even though neither the if or else statement are executing? 因此,即使if或else语句都没有执行,我也可以继续执行直到j <totalCols失败为止。

var rowCount = [];
for (var i = 0; i < totalRows; i++) {
   rowCount[i]="";
   spaceCount = 0;

   for (var j = 0; j < totalCols; j++) {
      if (puzzle[i][j] == "#") { // if this fails?
         spaceCount++;
         if (j == totalCols-1) rowCount[i] += spaceCount + "&nbsp;&nbsp;"; 
      } else {
         if (spaceCount > 0) { //and this fails?
            rowCount[i] += spaceCount + "&nbsp;&nbsp;";
            spaceCount = 0;
         } 
      }    
   }

}

No, if either of those if statements fails, you are still in the inner loop that is incrementing j . 不,如果这些if语句中的任何一个失败,则您仍处于递增j的内部循环中。 In order to get out of the inner loop you need to use the break statement. 为了摆脱内部循环,您需要使用break语句。

Nope, you first finish looping through the second loop and thus increment the j. 不,您先完成第二个循环,然后增加j。

    for (var j = 0; j < totalCols; j++) {

Only once you're done with that loop, do you go back to the 1st and increment the i. 只有在完成该循环后,您才返回第一个并递增i。

If the if statement fails the nested if won't execute. 如果if语句失败,则嵌套if将不会执行。 It goes to the else block and the loop continues until the condition i < totalRows is met. 转到else块,循环继续直到满足条件i < totalRows

If the if statement passes and the nested if fails, the loop still continues until i < totalRows is met. 如果if语句通过且嵌套if失败,则循环仍将继续直到满足i < totalRows

If both if statements passes the loop continues the condition until i < totalRows is met. 如果两个if语句均通过,则循环继续条件,直到满足i <totalRows。

What I am saying in essence is the if statement in the nested loop has nothing to do with the outer loop. 我实质上要说的是嵌套循环中的if语句与外部循环无关。

You can use the break statement to achieve this behavior. 您可以使用break语句来实现此行为。 edit: should have read the answers first. 编辑:应该先阅读答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM