- 我正在学习js
- 您能告诉我代码对于以下任务是否正确...
- 我能够打印 foo 和 bar
- 但无法打印 foobar
// Looping from 1 to 100 print out the following
// If the number is divisible by 3, log X foo
// if the number is divisible by 5, log X bar
// If the number is divisible by 15, log X foobar
// Only one output per number
// Expected output:
//
// 1
// 2
// 3 foo
// 4
// 5 bar
// 6 foo
// ...
// 15 foobar
// ...
// 100 bar
for(i=1; i<=100; i++){
console.log(i);
//var str = "";
if(i%3 == 0) {
//str = "foo";
console.log("foo");
}
else if(i%5 == 0) {
console.log("bar");
}
else if(i%3 == 0 && i%5 == 0) {
console.log("foobar");
}
}
最佳答案
您在 15 处仅得到“foo”的原因是因为 if (15%3 == 0)
计算结果为 true,并且您不会进入任何其他情况。
将 else if(i%3 == 0 && i%5 == 0)
移至顶部 if 情况。
for(i=1; i<=100; i++){
console.log(i);
if(i%3 == 0 && i%5 == 0) {
console.log("foobar");
}
else if(i%5 == 0) {
console.log("bar");
}
else if(i%3 == 0) {
console.log("foo");
}
}
这就是你想要的。
关于javascript - 无法在js中打印foobar只打印foo和bar,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28101468/