2 回答

TA贡献1784条经验 获得超7个赞
您需要返回随机值。
如果采用不带return语句的函数,则该函数undefined默认返回。
将该值用于加法运算undefined,然后通过加法将其转换为数字,但失败了,您将获得该值NaN,这意味着您将获得一个非数字的数字。任何带有NaNreturn的数字相加,NaN即您为两个玩家获得的值。
在这种情况下,NaN始终与和进行比较,false因此您永远不会获得成功的信息。
function RollDie() {
return Math.floor(Math.random() * 6) + 1;
// ^^^
}
var player1 = 0;
var player2 = 0;
player1 = RollDie() + RollDie() + RollDie() + RollDie() + RollDie();
player2 = RollDie() + RollDie() + RollDie() + RollDie() + RollDie();
console.log(player1);
console.log(player2);
if (player2 > player1) {
console.log("player 2 has won");
} else if (player2 < player1) {
console.log("player 1 has won");
}
console.log(undefined + undefined); // NaN
添加回答
举报