[英]can I use the 'switch' statement in any of the questions below? or is the 'else if' the right way to go?
I am trying to write a function that satisfies the following:我正在尝试编写满足以下条件的 function:
-count from 1 to 100, -on numbers divisible with 4 print “byfour”, -on numbers divisible with 6 print “bysix”, -on numbers divisible with both 4 and 6 print “byfoursix”, -skip numbers divisible with 7, -on the number 32 add '.', This is what I have, but I was wondering if there is way to use the switch statement. - 从 1 到 100 计数,-on 可被 4 整除的数字打印“byfour”,-on 可被 6 整除的数字打印“bysix”,-on 可被 4 和 6 整除的数字打印“byfoursix”,-跳过可被 7 整除的数字, - 在数字 32 上添加“。”,这就是我所拥有的,但我想知道是否有办法使用 switch 语句。 or any more optimal way to write it.
或任何更优化的方式来编写它。
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();
Any input or advice is super appreciated!任何意见或建议都非常感谢! Thank you
谢谢
It is possible to use a switch case if you wanted to by setting the switch parameter to true
so that it runs, although it's not necessarily a better way to write it.如果您愿意,可以通过将 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.