当我在 while 循环内创建一个随机数作为局部变量时,一切正常,但是当我生成一个随机数作为全局变量时,我就会陷入无限循环。
我不明白这会如何以及为什么会产生任何影响。
目标是通过 While 循环输出所有小于 0.7 的随机数。
这是创建无限循环的代码:
let rnd = Math.random();
let continue = true;
while (continue) {
console.log(rnd);
if (rnd > 0.7) {
continue = false;
alert(rnd + ' is bigger than 0.7!');
}
}
这是有效的代码(唯一改变的是随机数是在 while 循环内生成的)。
let continue = true;
while (continue) {
let rnd = Math.random();
console.log(rnd);
if (rnd > 0.7) {
continue = false;
alert(rnd + ' is bigger than 0.7!');
}
}
我对用另一种循环创建它不感兴趣,我只是想更好地理解 While 循环。
let rnd = Math.random();
let continue = true;
while (continue) {
console.log(rnd);
if (rnd > 0.7) {
continue = false;
alert(rnd + ' is bigger than 0.7!');
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)