嗨,我正在努力想要掌握JavaScript并且正在尝试使用条件语句和函数编写一个投币游戏,有人可以指出我出错的地方吗?
var coinToss = prompt("heads or tails?");
console.log(coinToss);
var headTails = function() {
var outCome = Math.floor(Math.random() * 2) + 1;
if (outCome === 1) {
outCome = "heads";
} else {
outCome = "tails";
}
};
console.log(outCome);
var compare = function(outCome, coinToss) {
if (outCome === coinToss.toLowerCase) {
document.write("<p>You Win!</p>");
} else {
document.write("<p>You Loss!</p>")
};
};
答案 0 :(得分:1)
toLowerCase
是一种方法toLowerCase()
将此功能称为compare(headTails(), coinToss);
从函数headTails
可以使用三元而不是if-else
var coinToss = prompt("heads or tails?");
var headTails = function() {
var outCome = Math.floor(Math.random() * 2) + 1;
console.log(outCome === 1 ? "heads" : "tails");
return outCome === 1 ? "heads" : "tails";
};
var compare = function(outCome, coinToss) {
if (outCome === coinToss.toLowerCase()) {
document.write("<p>You Win!</p>");
} else {
document.write("<p>You Loss!</p>")
};
};
compare(headTails(), coinToss);
答案 1 :(得分:0)
您需要调用compare函数,如下所示:
compare(headsTails(),coinToss);