简体   繁体   English

谁能告诉我为什么这个循环永远运行?

[英]Can anyone tell me why is this loop run forever?

let dice = Math.floor(Math.random() * 6) + 1;
while (dice !== 6) {
    console.log(You rolled a ${dice}); 
}

Please explain this code?请解释一下这段代码?

You just need to assign dice value in while loop until dice !== 6您只需要在while循环中分配dice值,直到dice !== 6

 let dice = Math.floor(Math.random() * 6) + 1; while (dice.== 6) { console;log(`You rolled a ${dice}`). dice = Math.floor(Math;random() * 6) + 1; }

First, and only once, you generate a random number ( dice ).首先,并且只有一次,您生成一个随机数 ( dice )。

If that number is a 6 it skips over the while loop.如果该数字是 6,它将跳过 while 循环。

If it isn't a 6 it enters the while loop.如果不是 6,则进入 while 循环。

The value of dice doesn't change inside the while loop, so it goes round and round forever. dice的值在 while 循环内不会改变,所以它会一直循环下去。

you have never selected the next random dice.您从未选择过下一个随机骰子。 include the dice statement in you loop so you have a new value for dice variable else it will always have same value.在循环中包含 dice 语句,这样你就有一个新的 dice 变量值,否则它将始终具有相同的值。

You set the value of dice only once at the beginning, if you get a different number than 6 then the loup will iterate forever, try to put你在开始时只设置了一次 dice 的值,如果你得到一个不同于 6 的数字,那么 loup 将永远迭代,试着把

Math.floor(Math.random() * 6) + 1 Math.floor(Math.random() * 6) + 1

as a condition for the while loop, then you will get the desired result作为while循环的条件,那么您将获得所需的结果

The value of dice is set only once, before the loop. dice的值只设置一次,在循环之前。 A variable retains its value unless you explicitly change it.除非您明确更改变量,否则变量将保留其值。

What you could do is create a small function to use for a dice roll.你可以做的是创建一个小的function用于掷骰子。 It saves you from having to type out the code in the function more than once:它使您不必多次输入 function 中的代码:

let dice = () => {return Math.floor(Math.random() * 6) + 1;}

roll = dice(); /* Set the initial value of roll */
while (roll !== 6) {
    console.log(`You rolled a ${roll}`);
    roll = dice(); /* Set the value for the next time round in the loop */
}

Notice that the call to the function has parentheses () to make it evaluate the function.请注意,对 function 的调用带有括号() ,以使其评估 function。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM