随机函数:防止以前的结果

时间:2018-03-01 10:46:19

标签: javascript jquery

我有一个带有随机结果的函数:

 document.getElementById('recaller').addEventListener('click', function() {
            var randomIndex = Math.ceil((Math.random() * 10) % randomStrings.length - 1);
            newText1 = randomStrings[randomIndex];
            newText2 = randomStrings2[randomIndex];
            answer2.innerHTML = newText2;
        });

以及此处的内容:

var randomStrings2 = [
    "1",
    "2",
    "3",
    "4",
    "5"
];

正确地说,有时在随机函数内,结果在2次“点击”内是相同的。如何防止先前的结果显示在下一次点击'尝试?

要想象我不想要那个结果:1,1,2,2,1,3 ......

但当然结果是好的1,2,3,1,2,4,5,1 ......

3 个答案:

答案 0 :(得分:2)

存储旧值,然后重复您的函数以计算函数,直到它们不相同为止。

        document.getElementById('recaller').addEventListener('click', function() {
            var lastValue = answer2.innerHTML;
            do{
            var randomIndex = Math.ceil((Math.random() * 10) % randomStrings.length - 1);
            newText1 = randomStrings[randomIndex];
            newText2 = randomStrings2[randomIndex];
            answer2.innerHTML = newText2;
            } while(lastValue == answer2.innerHTML);
        });

答案 1 :(得分:0)

您可以将结果存储在变量中,并将此变量与结果进行比较。像这样:

let savedNumber = 999;
const getRandomNumber = () => { return Math.ceil((Math.random() * 10) % randomStrings.length - 1) };

document.getElementById('recaller').addEventListener('click', function() {
            let randomIndex;
            while ((randomIndex = getRandomNumber()) == savedNumber)
                ;  
            savedNumber = randomIndex;
            newText1 = randomStrings[randomIndex];
            newText2 = randomStrings2[randomIndex];
            answer2.innerHTML = newText2;
        });

答案 2 :(得分:0)



var n=0;
var randomStrings = [1,2,3,4,5];
function shuffle(array) {
  var currentIndex = array.length, temporaryValue, randomIndex;
var lastEl=array[array.length-1];
  // While there remain elements to shuffle...
  while (0 !== currentIndex) {

    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    // And swap it with the current element.
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }
  if(lastEl===array[0])shuffle(array);
  
  return array;
}
document.getElementById('recaller').addEventListener('click', function() {
if(n===randomStrings.length){randomStrings=shuffle(randomStrings);n=0;}
          newText1 = randomStrings[n];
          n++;
            document.getElementById('answer2').innerHTML += newText1+'\n';
        });

<input type="button" id='recaller' value="generate random value">
<div style="display: inline-block" id="answer2">--</div>
&#13;
&#13;
&#13;