如何生成随机数并将其用于行动?

时间:2017-01-13 16:37:30

标签: javascript random splash

我的主要想法是产生某种“随机问候”,其想法是生成一个随机数,并依赖于显示“随机问候语”的数字。 这是我的非工作代码:

<p class="status">Your random splash screen: <span id="greeting">You don't have one</span></p>
<script>
var x = Math.floor((Math.random() * 4) + 1);
if (x == 1) {
  document.getElementById("greeting").innerHTML = "Greeting 1";
} else if (x == 2) {
  document.getElementById("greeting").innerHTML = "Greeting 2";
} else if (x == 3) {
  document.getElementById("greeting").innerHTML = "Greeting 3";
} else if (x == 4) {
  document.getElementById("greeting").innerHTML = "Greeting 4";
}
</script>

我不知道它有什么问题,请帮忙!

1 个答案:

答案 0 :(得分:0)

正如您在此处看到的,代码运行良好:

&#13;
&#13;
x +prefix= y;
&#13;
var x = Math.floor(Math.random() * 4);
var greetings = ['Greeting 1', 'Greeting 2', 'Greeting 3', 'Greeting 4'];

document.getElementById("greeting").innerHTML = greetings[x];
&#13;
&#13;
&#13;