繁体   English   中英

如何在另一个区域再次显示随机生成的字符串(来自数组)?

[英]How to display a randomly generated string (from array) again in another area?

基本上,我使用 HTML 和 JavaScript 来制作一个简单的石头剪刀布游戏,其中一个按钮激活从数组(石头、剪刀布或布)中随机生成的字符串。 我已经有了它,因此该按钮会随机生成一个计算机选择,并在下面的框中显示我的选择(使用单选按钮)。 我被卡住了,因为我不知道如何在另一个框中再次显示随机生成的计算机选择。

我尝试使用 if else 语句,但我不知道如何从数组中引用随机选择的字符串。 这是我之前在 html 游戏中尝试过的:

<script>
    function myFunction();{
    if (document.getElementById("randomSelect")) = 'rock'{
        document.getElementById('computerChoice').innerHTML = 'rock'
}       if (document.getElementById("randomSelect")) = 'paper'{
        document.getElementById('computerChoice').innerHTML = 'paper'
}       if (document.getElementById("randomSelect")) = 'scissors'{
        document.getElementById('computerChoice').innerHTML = 'scissors'
}
}
</script>
<p id = "computerChoice"></p>

另外,抱歉,如果这没有意义。 我是编码新手。

生成 0 到 2 之间的随机数(数组索引)。 将项目存储在数组中并根据生成的随机索引拉出。

 var items = ["rock", "paper", "scissors"]; document.getElementById("randomSelect").addEventListener('click', myFunction); function myFunction() { /*Generate random number between 0 and 2*/ var randomNum = Math.floor(Math.random() * 3); /*Set the random Item*/ document.getElementById('computerChoice').innerHTML = items[randomNum]; }

 <p id="computerChoice"></p> <button type="button" id="randomSelect">Random</button>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM