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?
-
Just add return keyworkd before randNum(arr,excludeNum);
return randNum(arr,excludeNum);
– MD SHAHIDUL ISLAM Commented Sep 29, 2013 at 7:34
4 Answers
Reset to default 4It 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
版权声明:本文标题:Generate one random index from an array but exclude one. javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745477596a2660032.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论