我可以在下面的任何问题中使用 'switch' 语句吗?或者 'else if' 是正确的方法吗?
can I use the 'switch' statement in any of the questions below? or is the 'else if' the right way to go?
我正在尝试编写满足以下条件的函数:
-从1数到100,
- 可被 4 整除的数字“byfour”,
- 可被 6 整除的数字打印“bysix”,
- 可同时被 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);
}
}
我正在尝试编写满足以下条件的函数:
-从1数到100, - 可被 4 整除的数字“byfour”, - 可被 6 整除的数字打印“bysix”, - 可同时被 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);
}
}