如何在JavaScript中生成随机数?

时间:2016-04-17 15:07:13

标签: javascript arrays for-loop random

我有4个跨度,我希望用数组中已有的值填充这些跨度,问题是我不是第一个跨度中的第一个值gos我想要的是每个值采用随机跨度

<span id="optiona"></span>
<span id="optionb"></span>
<span id="optionc"></span>
<span id="optiond"></span>

该数组上的每个值

var op1 = Math.floor(Math.random()*9563);
var op2 = Math.floor(Math.random()*1457);
var op3 = Math.floor(Math.random()*8547);
var answers = [op1,op2,op3,rightAnswer]

我想做的是

var answerDisplay = document.querySelectorAll(".answers span");
for(i=0;i<answers.length;i++){
    answerDisplay[i].textContent = answers[rand()];
}
function rand(){
    var randomN =  Math.floor(Math.random()*answers.length);
    return randomN;
}

我的问题是如何生成随机数而不重复?

1 个答案:

答案 0 :(得分:0)

var answerDisplay = document.querySelectorAll(".answers span");
var assigned = [];
for(i=0;i<answers.length;i++){
    var index = newRand(assigned);
    assigned.push(index);
    answerDisplay[i].textContent = answers[index];
}
function newRand(assigned){
    var r = rand();
    while (assigned.indexOf(r) >= 0){
        r = rand();
    }
    return r;
}
function rand(){
    var randomN =  Math.floor(Math.random()*answers.length);
    return randomN;
}