为什么我的随机整数生成器总是返回1?

时间:2016-02-18 19:29:15

标签: javascript

我试图通过制作随机整数生成器来练习。这是我到目前为止所得到的。我认为它将返回1到6之间的随机整数(包括),但它总是返回1.为什么这样做?



function run() {
  var number = Math.floor(Math.random() * 5) + 1;

  if (number = 1) {
    document.getElementById("main").innerHTML = "1";
  } else if (number = 2) {
    document.getElementById("main").innerHTML = "2";
  } else if (number = 3) {
    document.getElementById("main").innerHTML = "3";
  } else if (number = 4) {
    document.getElementById("main").innerHTML = "4";
  } else if (number = 5) {
    document.getElementById("main").innerHTML = "5";
  } else {
    document.getElementById("main").innerHTML = "6";
  }
};

<!DOCTYPE html>
<html>

<head>
  <script src="script.js"></script>
  <link rel="stylesheet" type="text/css" href="stylesheet.css">
  <title>Insults Generator</title>
</head>

<body>
  <h1 id="main">-</h1>
  <button onClick="run()">GENERATE</button>


</body>

</html>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:1)

比较两个值时应该有两个或三个相等的符号,但如果要为变量赋值,则只有一个(就像你在第一行中一样)

var number = Math.floor(Math.random() * 5) + 1;

if (number == 1) {
    document.getElementById("main").innerHTML = "1";
}
else if (number == 2) {
    document.getElementById("main").innerHTML = "2";
} 
else if (number == 3) {
    document.getElementById("main").innerHTML = "3";
} 
else if (number == 4) {
    document.getElementById("main").innerHTML = "4";
} 
else if (number == 5) {
    document.getElementById("main").innerHTML = "5";
} 
else {
    document.getElementById("main").innerHTML = "6";
}

要了解两个和三个等号之间的区别,请看这里:

Which equals operator (== vs ===) should be used in JavaScript comparisons?

答案 1 :(得分:0)

var number = Math.floor(Math.random() * 5) + 1;

if (number <= 6 && number >=1) {
    document.getElementById("main").innerHTML = number;

}

你不需要6个if语句,只需要一个!

答案 2 :(得分:-1)

'='和'=='之间存在差异。如果条件,请尝试使用“==”而不是“=” 例如:if ( x == 2 )