admin管理员组

文章数量:1426800

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?

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?

Share Improve this question asked Sep 29, 2013 at 7:14 SkizoSkizo 5412 gold badges8 silver badges14 bronze badges 1
  • Just add return keyworkd before randNum(arr,excludeNum); return randNum(arr,excludeNum); – MD SHAHIDUL ISLAM Commented Sep 29, 2013 at 7:34
Add a ment  | 

4 Answers 4

Reset to default 4

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);.

Here is an updated version that looks up the indexes, removes the unwanted one, and picks random from the others. I use it to shuffle a playlist.

function randomIndex(arr, excludeIndex){
    let indexes = Object.keys(arr); //get a list of indexes
    indexes.splice(excludeIndex, 1); //remove the unwanted
    return indexes[Math.floor(Math.random() * indexes.length)]; //pick a new index
}

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?

本文标签: Generate one random index from an array but exclude one javascriptStack Overflow