Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
175 views
in Technique[技术] by (71.8m points)

javascript - How would I prevent a random function from choosing the last outcome of that function when run another time?

I have a function choosing a random item from an array. I'm trying to figure out how I can run this function so that the next time it is run, it excludes the previous choice as to not repeat choices.

var itemArray= [
    {
        name: 'Apple'
    },
    {
        name: 'Orange'
    },
    {
        name: 'Banana'
    }
];

var itemLength = itemArray.length;

var randomNumber = Math.floor(Math.random() * legendLength) + 0;
var randomPick = itemArray[randomNumber];

document.getElementById("item").innerHTML = '<b>' + randomPick.name;

I'm sure this is a simple fix I just can't seem to work it out. Any help would be greatly appreciated.

question from:https://stackoverflow.com/questions/65847035/how-would-i-prevent-a-random-function-from-choosing-the-last-outcome-of-that-fun

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you just want to "remember" the last result, you can do something like this:

var itemArray= [
{
    name: 'Apple'
},
{
    name: 'Orange'
},
{
    name: 'Banana'
}
];

var itemLength = itemArray.length;

var randomNumber = ""
var oldNumber = 1

function getRandomNumber(){
do{
    randomNumber = Math.floor(Math.random() * itemLength) + 0;
}
while(randomNumber === oldNumber)

oldNumber = randomNumber
var randomPick = itemArray[randomNumber];

document.getElementById("item").innerHTML = '<b>' + randomPick.name;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...