![](/img/trans.png)
[英]How to omit 0 from array of randomly generated numbers using Javascript?
[英]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.