我正在研究一個項目,該項目將根據隨機生成的數字爲我提供隨機城鎮財富。然而,每當我按下「建立鄉鎮」按鈕,我總是會變得「富有」。如何修復我的代碼以啓用期望的結果?爲什麼我的隨機數發生器總是給我一個?
<!DOCTYPE html>
<html>
<body>
<style>
h1 {font-size: 20pt; color: red;}
p {font-size: 17pt; color: blue;}
p2 {font-size: 18pt; color: orange;}
p3 {font-size: 18pt; color: green;}
</style>
<p>This program will create a random town upon the click of a button.</p>
<button onclick="numberdescription()">Establish Township</button>
<br /><br /><br />
<p3 id="random"></p3>
<script>
function numberdescription() {
var num = Math.floor(Math.random() * 3 + 1)
if (num = 1) {
desc = "wealthy";
} else if (num = 2) {
desc = "middle wealth";
} else {
desc = "dirt poor";
}
document.getElementById("random").innerHTML = desc;
}
</script>
</body>
</html>
您正在比較'=='(比較)的'='(賦值)intead。因此,if語句在執行時將'num'設置爲'1'。 – Pointy
強制性的JavaScript單行:'document.getElementById(「random」)。innerHTML = [「richy」,「middle wealth」,「dirt poor」] [Math.floor(Math.random()* 3)];'' 。真正的問題是,爲什麼有相同數量的貧窮和富裕的城鎮? – Pluto