首页 > 解决方案 > While 循环完成但打印其所有变量

问题描述

我对 的逻辑有点困惑while loop。假设这样一个最小的代码:

var i = 1; // Set counter to 1
var msg = ''; // Message

// Store 5 times table in a variable
while (i < 10) {
  msg += i + ' x 5 = ' + (i * 5) + "\n";
  i++;
}
console.log(msg) // the console is placed out of {}

运行它并通过:

1 x 5 = 5
2 x 5 = 10
3 x 5 = 15
4 x 5 = 20
5 x 5 = 25
6 x 5 = 30
7 x 5 = 35
8 x 5 = 40
9 x 5 = 45

我猜它只会输出:

9 x 5 = 45

因为,while 循环在 i = 9 处停止,并console.log(msg)在 while 循环完成后执行,因为它不在 {} 内,

然而,结果出乎我的意料。怎么理解?

标签: javascript

解决方案


msg += i + ' x 5 = ' + (i * 5) + "\n";

该行适用于每个数字,并且您要附加到字符串。该字符串继续占用 1-9 的每一行,最后当您执行 console.log 时,它删除了整个字符串。将 console.log 放入 while 以查看字符串在每个循环中的增加。比如 1,然后是 1,2,然后是 1,2,3,以此类推。


推荐阅读