JavaScript 如何忽略else条件中的循环
在本文中,我们将看到使用JavaScript忽略else条件中循环的方法。有 两种方法 可以在else条件中忽略循环:
- Continue
- Break
简而言之, Break 语句会退出循环,而 Continue 语句会跳出当前迭代。让我们通过一些示例进一步理解。
示例1: 带有continue语句的for循环:
<script type="text/javascript" charset="utf-8">
// 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);
}
</script>
输出:
0
2
示例2: 带有break语句的for循环:
<script type="text/javascript" charset="utf-8">
// 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);
}
</script>
输出:
0
For eachloop: 当涉及到forEach循环时,AngularJS使用break和continue语句会变得非常混乱。break和continue语句无法按预期工作,实现continue的最佳方式是使用return语句,无法在forEach循环中实现break。
// 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