sách gpt4 ai đã đi

javascript - 了解 while 循环

In lại 作者:行者123 更新时间:2023-12-03 21:18:19 25 4
mua khóa gpt4 Nike

我是 Javascript 的新手,我正在尝试绕过 while 循环。我了解它们的目的,我想我了解它们的工作原理,但我在使用它们时遇到了麻烦。

我希望 while 值自身重复,直到两个随机数相互匹配。目前,while 循环只运行一次,如果我想让它自己重复,我需要再次运行它。

如何设置此循环,使其自动重复 if 语句,直到 diceRollValue === compGuess?谢谢。

diceRollValue = Math.floor(Math.random()*7);
compGuess = Math.floor(Math.random()*7);
whileValue = true;

while (whileValue) {
if (diceRollValue === compGuess) {
console.log("Computer got it right!")
whileValue = false;
}
else {
console.log("Wrong. Value was "+diceRollValue);
whileValue = false;
}
}

1 Câu trả lời

那是因为您只是在 while 之外执行随机数生成器。如果您想要两个新数字,则需要在 while 语句中 执行它们。类似于以下内容:

var diceRollValue = Math.floor(Math.random() * 7),
compGuess = Math.floor(Math.random() * 7),
whileValue = true;
while (whileValue){
if (diceRollValue == compGuess){
console.log('Computer got it right!');
whileValue = false; // exit while
} khác {
console.log('Wrong. Value was ' + diceRollValue);
diceRollValue = Math.floor(Math.random() * 7); // Grab new number
//whileValue = true; // no need for this; as long as it's true
// we're still within the while statement
}
}

如果你想重构它,你也可以使用 phá vỡ 来退出循环(而不是使用变量):

var diceRollValue = Math.floor(Math.random() * 7),
compGuess = Math.floor(Math.random() * 7);
while (true){
if (diceRollValue == compGuess){
// breaking now prevents the code below from executing
// which is why the "success" message can reside outside of the loop.
phá vỡ;
}
compGuess = Math.floor(Math.random() * 7);
console.log('Wrong. Value was ' + diceRollValue);
}
console.log('Computer got it right!');

关于javascript - 了解 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12946193/

25 4 0
行者123
Hồ sơ cá nhân

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá Didi Taxi miễn phí
Mã giảm giá Didi Taxi
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com