简体   繁体   中英

Generate one random index from an array but exclude one. javascript

I need to generate one random number from an array but exclude one index and return the index of the random number.
I tried this:

function randNum(arr,excludeNum){
    var randNumber = Math.floor(Math.random()*arr.length);
    if(arr[randNumber]==excludeNum){
        randNum(arr,excludeNum);
    }else{
        return randNumber;
    }
}
alert(randNum([7, 10, 11],7));

But somtimes it returns the numbers I want it to return and sometimes it returns undefined.
What is the problem?

It is because your function doesn't return anything when the generated random number is the one you want to exclude. Add a return to the randNum function call in the if clause.

function randNum(arr,excludeNum){
    var randNumber = Math.floor(Math.random()*arr.length);
    if(arr[randNumber]==excludeNum){
        return randNum(arr,excludeNum);
    }else{
        return randNumber;
    }
}
alert(randNum([7, 10, 11],7));

You need a return keyword in front of randNum(arr,excludeNum); .

Because you are using floor and eventually the stack will fill up. (also I think that you missed return)

Why not just remove that number from the array and chose a random index into the rest of it?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM