javascript - 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 循环完成后执行,因为它不在 {} 内,
然而,结果出乎我的意料。怎么理解?
解决方案
msg += i + ' x 5 = ' + (i * 5) + "\n";
该行适用于每个数字,并且您要附加到字符串。该字符串继续占用 1-9 的每一行,最后当您执行 console.log 时,它删除了整个字符串。将 console.log 放入 while 以查看字符串在每个循环中的增加。比如 1,然后是 1,2,然后是 1,2,3,以此类推。
推荐阅读
- php - 返回其子类的新实例的方法
- python - 在相同数量的 bin 中绘制相同数量的点并平均 bin 值
- django - Django Haystack中的date_facet没有按日期分面
- html - VBA 到 VBS - iframe 权限被拒绝
- javascript - 我可以对外部脚本加载的 HTML 进行 dom 操作吗?
- c++ - 如何将不同模板参数值但类型相同的值放入此类型的变量中?C++
- c# - 检查数据库中是否已经存在记录
- docker - docker - 在构建期间将参数传递给脚本
- javascript - 使用 use-scroll-position 滚动后,如何将 className 添加到 React 组件?
- javascript - 如何选择在另一个属性中具有特定值的标记的 XML 属性值?