Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
176 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 Reply

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...