gpt4 book ai didi

javascript - 用函数改变Javascript变量?

转载 作者:行者123 更新时间:2023-12-02 14:39:38 24 4
gpt4 key购买 nike

我可以用 var computerChoice = Math.random(); 来做到这一点……并将该变量变成石头、布或剪刀……但现在我无法获得变量“winner” ' 进行更改,以便打印出结果。它只是不断打印出“未定义”。帮助?

 var choice1 = userChoice;
var choice2 = computerChoice;


var winner = "undefined";


var compare = function (choice1, choice2) {//start function

if (choice1 === choice2) {
winner = "Tie game!";


} else if (choice1 === "rock") {
if (choice2 === "scissors") {
winner = "rock wins";
} else {
winner = "paper wins";
}
} else if (choice1 === "paper") {
if (choice2 === "rock") {
winner = "paper wins";
} else {
winner = "scissors wins";
}
} else {
if (choice2 === "paper") {
winner = "scissors wins";
} else {
winner = "rock wins";
}
}

}//end function


confirm("You chose: " + userChoice + "\nSystem: " + computerChoice + "\nOutcome: " + winner);


compare(userChoice,computerChoice);

</script>

最佳答案

那是因为您在显示它之前没有对其进行更改。 调用confirm之前调用compare,因为compare是改变winner的函数。

compare(userChoice, computerChoice);
confirm("You chose: " + userChoice + "\nSystem: " + computerChoice + "\nOutcome: " + winner);

关于javascript - 用函数改变Javascript变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37125198/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com