无法在 js 中打印 foobar 只能打印 foo 和 bar

Not able to print foobar in js only prints foo and bar

本文关键字:打印 foo bar foobar js      更新时间:2023-09-26
  1. 我正在学习 js
  2. 你能告诉我以下任务的代码是否正确吗......
  3. 我能够打印foo和酒吧
  4. 但无法打印福巴

http://jsfiddle.net/1u1o2es7/

// 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)移到顶部。

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 的编译器。只需按 f12 并转到脚本部分,您就可以设置一个断点并查看 javascript 引擎在做什么。