Javascript Random Name Always Returning Same item

问题: I have this javascript code that collects the name from an array of string and return a random name, But everytime I fire the function, it is returning the same name; I nee...

问题:

I have this javascript code that collects the name from an array of string and return a random name, But everytime I fire the function, it is returning the same name; I need to refresh the web page to generate a new random name.

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>


回答1:

You need to put the random function inside your getRandom() function

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>


回答2:

You create only once and never change randomItem - that is why you're getting always the same item. Simplyfy your code as follows:

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>

  • 发表于 2018-09-02 20:24
  • 阅读 ( 315 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除