Javascript while循环向上打印1到10,但返回11
我再次在CodeAcademy工作,我一直在继续工作,现在正在使用while循环。然而,我在草稿行中做了一点工作,我注意到了一些奇怪的事情。 此代码位于此文本的正下方:Javascript while循环向上打印1到10,但返回11,javascript,loops,while-loop,Javascript,Loops,While Loop,我再次在CodeAcademy工作,我一直在继续工作,现在正在使用while循环。然而,我在草稿行中做了一点工作,我注意到了一些奇怪的事情。 此代码位于此文本的正下方: var counter = 1; while(counter <= 10){ console.log(counter); counter = counter + 1; } 条件计数器我正在Firefox中测试,它正在记录OP所说的内容。。这是我对它的看法 var计数器=1 1 is it <= 1
var counter = 1;
while(counter <= 10){
console.log(counter);
counter = counter + 1;
}
条件计数器我正在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.
这是控制台的行为。在某些情况下,它将返回最后一个表达式的结果
var counter = 1, t="loop";
while(counter <= 10){
console.log(counter);
counter = counter + 1;
t = "loop end";
}
你应该这样做
var counter = 0;
while(counter < 10){
console.log(counter);
counter = counter + 1;
}
var计数器=0;
while(计数器<10){
控制台日志(计数器);
计数器=计数器+1;
}
当(计数器我只能得到1到10个值即使我只能得到1到10个值:P,在这里发布完整的js代码相同,我只能得到1到10个值:打印的值必须是1到10个值,但是循环完成后,
counter
将包含11
。由于以下语句:counter=counter+1;
,它增加了计数器的值按1编码>并再次将其分配给计数器。坏主意…你最多只能得到9不,@louisbros,循环结束后你正在检查值,这就是为什么它是10。我认为这不是完全正确的louisbros。如果我这样做,我只会得到9。我想得到10,结果是10。如果你知道怎么做的话?我是just解释为什么循环结束后count的值是11。如果您想看到10在递增之后放入日志消息aha,我明白了…:)有什么方法可以放弃对after 11值的限制吗?有什么方法吗?如果您想了解更多信息,可以通过这个问题。这就是console行为类似这样的原因。
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
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"
var counter = 0;
while(counter < 10){
console.log(counter);
counter = counter + 1;
}