Javascript随机名称总是返回相同的项目

时间:2018-08-30 11:17:30

标签: javascript html random

我有这个javascript代码,它从字符串数组中收集名称并返回一个随机名称,但是每次我触发该函数时,它都返回相同的名称;我需要刷新网页以生成新的随机名称。

var items = ["Tony","Peter","Chris","Thor","Roger","Steve"];
var  randomItem = items[Math.floor(Math.random() * items.length)];

function getRandom(){
  document.getElementById("random").innerHTML = randomItem;
}
<button id="getRandom" onclick="getRandom()">Get Random name</button>
<span id="random">Click button to generate new name</span>

2 个答案:

答案 0 :(得分:6)

您需要将随机函数放入getRandom()函数中

var items = ["Tony","Peter","Chris","Thor","Roger","Steve"];


function getRandom(){
  var  randomItem = items[Math.floor(Math.random() * items.length)];
  document.getElementById("random").innerHTML = randomItem;
}
<button id="getRandom" onclick="getRandom()">Get Random name</button>
<span id="random">Click button to generate new name</span>

答案 1 :(得分:0)

您只创建一次,就永远不会更改randomItem-这就是为什么您总是得到同一项目的原因。只需如下代码即可:

var items = ["Tony","Peter","Chris","Thor","Roger","Steve"];

function getRandom(){
  document.getElementById("random").innerHTML = items[Math.floor(Math.random() * items.length)];
}
<button id="getRandom" onclick="getRandom()">Get Random name</button>
<span id="random">Click button to generate new name</span>