![](/img/trans.png)
[英]How can I convert this if, else if statement to switch-statement?
[英]can I use the 'switch' statement in any of the questions below? or is the 'else if' the right way to go?
我正在尝试编写满足以下条件的 function:
- 从 1 到 100 计数,-on 可被 4 整除的数字打印“byfour”,-on 可被 6 整除的数字打印“bysix”,-on 可被 4 和 6 整除的数字打印“byfoursix”,-跳过可被 7 整除的数字, - 在数字 32 上添加“。”,这就是我所拥有的,但我想知道是否有办法使用 switch 语句。 或任何更优化的方式来编写它。
function maths(){
for (let i=1; i<=100; i++){
if (i === 32){
console.log (`${i}!`);
}
else if (i % 4 === 0 && i % 6 === 0){
console.log ("byfoursix");
}
else if (i % 4 ===0) {
console.log ("byfour");
}
else if (i % 6 === 0) {
console.log ("bysix");
}
else if (i % 7 === 0){
continue;
}
else {
console.log (i);
}
}
}
maths();
任何意见或建议都非常感谢! 谢谢
如果您愿意,可以通过将 switch 参数设置为true
来使用 switch case 以便它运行,尽管它不一定是更好的编写方式。
for (let i = 1; i <= 100; i++) {
switch (true) {
case (i === 32):
console.log(`${i}!`);
break;
case (i % 4 === 0 && i % 6 === 0):
console.log('byfoursix');
break;
case (i % 4 === 0):
console.log('byfour');
break;
case (i % 6 === 0):
console.log('bysix');
break;
case (i % 7 === 0):
break;
default:
console.log(i);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.