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

有两种办法能够在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

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理