gpt4 book ai didi

javascript - 为什么我的随机数生成器总是给我一个?

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

我正在开发一个项目,该项目将根据随机生成的数字为我提供随机的城镇财富。然而,每当我按下“建乡”按钮时,我总是“发财”。如何修复我的代码以实现所需的结果?

<!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>

最佳答案

= 被视为 assignment operator 。您需要相等运算符 ==,即 comparison operator

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;
}

关于javascript - 为什么我的随机数生成器总是给我一个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37556765/

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