gpt4 book ai didi

javascript - 根据虚拟代理的随机选择产生不同结果的函数

转载 作者:行者123 更新时间:2023-11-28 17:05:52 25 4
gpt4 key购买 nike

我正在尝试定义一个函数,该函数根据虚拟合作伙伴的随机选择产生不同的结果。游戏是通过提交来实现的。我创建了一个数组,然后随机选择。接下来我尝试实现一个具有多个条件的 if 语句。但它不会返回警报。感谢您的意见。

<h1>What is your choice?</h1><br>
<form id="d1">
<input type="radio" name="choice" value="Cooperate"> Cooperate
<input type="radio" name="choice" value="Betray"> Betray
</form>
<button onclick="submitAnswer()">Submit Answer</button>
<script>
function submitAnswer() {
var selected = document.querySelector('input[type="radio"]:checked').value;
var myArray = ['Cooperate', 'Betray'];
var rand = myArray[Math.floor(Math.random() * myArray.length)];
if (selected === "Cooperate" || rand === "Cooperate") {
alert("2");
} else if (selected === "Betray" || rand === "Cooperate") {
alert("3");
} else if (selected === "Cooperate" || rand === "Betray") {
alert("0");
} else if (selected === "Betray" || rand === "Betray") {
alert("1");
}
}
</script>

最佳答案

你有一些流氓括号。在 Javascript 中,整个条件子句必须用括号括起来。另外,为了防止自动提交,请将按钮的类型设置为“button”。试试这个:

<h1>What is your choice?</h1><br>
<form id="d1">
<input type="radio" name="choice" value="Cooperate"> Cooperate
<input type="radio" name="choice" value="Betray"> Betray
</form>
<button type="button" onclick="submitAnswer()">Submit Answer</button>
<script>
function submitAnswer() {
var selected = document.querySelector('input[type="radio"]:checked').value;
var myArray = ['Cooperate', 'Betray'];
var rand = myArray[Math.floor(Math.random() * myArray.length)];
if (selected === "Cooperate" || rand === "Cooperate") {
alert("2");
} else if (selected === "Betray" || rand === "Cooperate") {
alert("3");
} else if (selected === "Cooperate" || rand === "Betray") {
alert("0");
} else if (selected === "Betray" || rand === "Betray") {
alert("1");
}
}
</script>

关于javascript - 根据虚拟代理的随机选择产生不同结果的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55883474/

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