关于javascript:JavaScript如何在else条件中忽略循环

6次阅读

共计 1233 个字符,预计需要花费 4 分钟才能阅读完成。

有两种办法能够在 else 条件下疏忽循环:

  • continue
  • break

简略地说,Break 语句退出循环,而 continue 语句退出特定迭代。

让咱们通过一些例子进一步了解。

应用 continue 语句的 for 循环:

// Defining the variable
var i;
  
// For loop 
for (i = 0; i < 3; i++) {
    
     // If i is equal to 1, it
     // skips the iteration
     if (i === 1) {continue ;}
  
     // Printing i
     console.log(i);
}

输入如下:

0
2

带 Break 语句的 for 循环:

// Defining the variable
var i;
  
// For loop 
for (i = 0; i < 3; i++) {
  
     // If i is equal to 1, it comes
     // out of the for a loop
     if (i === 1) {break ;}
  
     // Printing i
     console.log(i);
}

输入如下:

0

对于每个循环:当波及到 forEach 循环时, AngularJS 的 break 和 continue 语句变得十分凌乱。

break 和 continue 语句无奈按预期工作, 实现 continue 的最佳办法是应用 return 语句, 该 break 不能在 forEach 循环中实现。

// Loop which runs through the array [0, 1, 2]
// and ignores when the element is 1
angular.forEach([0, 1, 2], function (count){if (count == 1) {return true ;}
  
     // Printing the element
     console.log(count);
});

输入如下:

0
2

然而, 能够通过蕴含一个布尔函数来实现 break 动作, 如上面的示例所示:

// A Boolean variable
var flag = true ;
  
// forEach loop which iterates through
// the array [0, 1, 2]
angular.forEach([0, 1, 2], function (count){
    
     // If the count equals 1 we
     // set the flag to false
     if (count==1) {flag = false ;}
  
     // If the flag is true we print the count
     if (flag){console.log(count); }
});

输入如下:

0

更多前端开发相干内容请参考:lsbin – IT 开发技术:https://www.lsbin.com/

查看以下更多 JavaScript 相干的内容:

  • JavaScript 如何应用正则表达式?:https://www.lsbin.com/3805.html
  • JavaScript 查看元素是否是父元素的子元素?:https://www.lsbin.com/3652.html
  • JavaScript 性能问题和优化指南:https://www.lsbin.com/3573.html
正文完
 0