我再次在CodeAcademy中工作,我一直在继续工作,现在正在使用while循环。然而,我在便签上工作了一点,我注意到了一些奇怪的事情。这段代码就在文本下面:
var counter = 1;
while(counter <= 10){
console.log(counter);
counter = counter + 1;
}
结果是这样的。为什么11会出现在底部。它不应该在那里。算0吗。或者对此还有什么更痛苦的解释。很乐意得到帮助,谢谢
结果:
1
2
3
4
5
6
7
8
9
10
==> 11
发布于 2013-03-06 08:08:16
我正在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
发布于 2013-03-06 08:25:41
这是控制台的行为。在某些情况下,它将返回最后一个表达式的结果。
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"
发布于 2016-02-19 01:40:42
你应该这么做。
var counter = 0;
while(counter < 10){
console.log(counter);
counter = counter + 1;
}
虽然(计数器<= 10)说,虽然计数器小于或等于10,它会做循环,这就是为什么数字11也被打印出来。
https://stackoverflow.com/questions/15241612
复制相似问题