【问题标题】:while loop prints 1 up and to 10, but gives back 11while 循环打印 1 到 10,但返回 11
【发布时间】:2013-03-06 07:41:14
【问题描述】:

我再次在 CodeAcademy 工作,我一直在继续工作,现在正在使用 while 循环。然而,我在草稿本上工作了一点,我注意到了一些奇怪的东西。 这段代码就在这段文字的正下方:

var counter = 1;

while(counter <= 10){
    console.log(counter);
    counter = counter + 1;
}

作为结果给出这个。 为什么底部会弹出 11。它不应该在那里。是算 0。还是对此有更苦涩的解释。很高兴得到一些帮助,谢谢:P

结果:

1
2
3
4
5
6
7
8
9
10
==> 11 

【问题讨论】:

  • 我只得到 1 到 10 个
  • 即使我只得到 1 到 10 :P,发布你的完整 js 代码
  • 这里也一样,我只得到 1 到 10:jsfiddle.net/gAu2x
  • 打印的值必须是 1 到 10,但循环结束后counter 将包含11
  • 由于这条语句:counter = counter + 1;,它把counter的值加1,并再次赋值给counter

标签: javascript loops while-loop


【解决方案1】:

这是控制台的行为。在某些情况下它会返回最后一个表达式的结果

var counter = 1, t="loop";

while(counter <= 10){
    console.log(counter);
    counter = counter + 1;
    t = "loop end";
}

会给你

1
2
3
4
5
6
7
8
9
10
"loop end"

【讨论】:

【解决方案2】:

我正在 Firefox 中进行测试,它正在记录 OP 所说的内容。这是我的看法。

var 计数器 = 1;

1 is it <= 10 yes, print add 1
2 is it <= 10 yes, print add 1
3 is it <= 10 yes, print add 1
4 is it <= 10 yes, print add 1
5 is it <= 10 yes, print add 1
6 is it <= 10 yes, print add 1
7 is it <= 10 yes, print add 1
8 is it <= 10 yes, print add 1
9 is it <= 10 yes, print add 1
10 is it <= 10 yes, print add 1
11  <-- prints it. 

while 循环在传入时知道“计数器”,而不是在声明“之后”或在循环内。它没有反向引用。所以还是得再过一遍。

before: 1

after: 2

before: 2

after: 3

before: 3

after: 4

before: 4

after: 5

before: 5

after: 6

before: 6

after: 7

before: 7

after: 8

before: 8

after: 9

before: 9

after: 10

before: 10

after: 11

【讨论】:

  • 啊哈,我明白了... :) 有什么方法可以放弃 11 后值的 pprinting 吗?有什么办法吗?
【解决方案3】:

你应该这样做。

var counter = 0;

while(counter < 10){
    console.log(counter);
    counter = counter + 1;
}

while(counter

【讨论】:

    【解决方案4】:

    条件 'counter

    将条件改为'counter

    这将导致 1 - 10 并且离开计数为 10:

    var counter = 0;
    
    while(counter < 10){
        counter = counter + 1;
        console.log(counter);
    }
    

    【讨论】:

    • 坏主意...你最多只能得到 9 个
    • 不,@louisbros,您在循环结束后检查值,这就是为什么它是 10。
    • 我认为这不是完全正确的 louisbros。如果我这样做,我最多只能达到 9 点。我想达到 10 个结果,结果是 10 个。如果您对如何做到这一点有一些想法?
    • 我只是在解释为什么循环结束后count的值是11。
    • 如果想看10放后增量后的日志信息
    猜你喜欢
    • 1970-01-01
    • 2023-01-29
    • 2016-05-22
    • 1970-01-01
    • 2021-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-05
    相关资源
    最近更新 更多