不能在js中打印foobar只打印foo和bar

时间:2015-01-23 01:05:04

标签: javascript jquery function loops javascript-events

  1. 我正在学习js
  2. 你能告诉我代码是否适合以下任务......
  3. 我可以打印foo和bar
  4. 但无法打印foobar
  5. 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");
        }
    }
    

2 个答案:

答案 0 :(得分:1)

你在15岁时只获得“foo”的原因是因为if (15%3 == 0)评估为真,而你没有进入任何其他情况。

如果是的话,将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");
    }
}

这就是你想要的。

答案 1 :(得分:0)

您可以使用浏览器开发人员工具逐步浏览javascript编译器。只需点击f12并转到Scripts部分,您就可以设置一个断点并查看javascript引擎正在做什么。