如何用JavaScript忽略else条件下的循环
有两种方法可以忽略else条件下的循环。
- Continue
- Break
简单地说,Break语句退出了循环,而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
对于每个循环: AngularJS在forEach循环中使用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
然而,断裂的动作可以通过包括一个布尔函数来实现,正如下面的例子所实现的那样。
// 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