我尝试在for循环中使用continue来跳过每5次迭代。但是,我只知道如何写continue,其中只需跳过第一个5。不确定如何实现continue语句才能使其工作。正确的输出应该是:
1 is odd.
2 is even.
3 is odd.
4 is even.
6 is even.
7 is odd.
8 is even.
9 is odd.
11 is odd.
12 is even.
13 is odd.
14 is even.
16 is even.
17 is odd.
18 is even.
19 is odd.这是我的代码。
forwardOp(1,20)
function forwardOp(startIndex, endIndex){
if (startIndex > endIndex){
console.log("Start number cannot be less than End number.");
}
for (i = startIndex; i <= endIndex; i++){
if (i === 5){continue;}
if (i % 2 ==0){
console.log (i," is even.")
}else {
console.log (i, " is odd.")
}
}
}发布于 2021-08-13 00:18:20
您必须使用i % 5 == 0。
为了简单起见,下面是修复后的代码:
forwardOp(1,20)
function forwardOp(startIndex, endIndex){
if (startIndex > endIndex){
console.log("Start number cannot be less than End number.");
}
for (i = startIndex; i <= endIndex; i++){
if (i % 5 == 0){
// 'i' is divisible by 5
}
if (i % 2 ==0){
console.log (i," is even.")
} else {
console.log (i, " is odd.")
}
}
}发布于 2021-08-13 00:10:06
与模块2相同
if (i % 5==0){
console.log (i," is divisible by 5.")
}发布于 2021-08-13 00:13:15
if (i === 5){continue;}行表示跳过第5行。如果你想每隔5行跳过一次,你应该使用模: If (i%5 == 0){continue;}
https://stackoverflow.com/questions/68765402
复制相似问题