javascript - 如何在相同可能性的一百中选择一个?JS
问题描述
我正在构建一个音乐播放器,我想创建随机功能,我现在使用 math.random 这显然是个坏主意,因为它可以多次重复相同的数字,所以我需要给他们同样的机会,但没有清楚怎么做,现在我有一个包含三首音乐的数组,所以如果随机点击其中一个应该播放,如果我再次点击下一个,但从来没有两次相同的歌曲,我该怎么做?
解决方案
虽然已经在评论中得到了回答,但这里是 javascript 代码示例:
// your playlist length
let playlistLength = 10;
// temporary variables
let src = [], res = [], idx, len;
// fill the 'src' array with numbers from 0 to playlistLength-1
for (idx = 0; idx < playlistLength; idx++) src.push(idx);
// while the 'src' array has any elements
while (len = src.length) {
// get random element index in 0 .. src.length-1 range
idx = Math.floor(Math.random() * len);
// push the element into the array 'res'
res.push(src[idx]);
// remove the element from array 'src'
src.splice(idx, 1);
}
// here is random sequence of numbers from 0 to playlistLength-1
console.log(res.join(', '));
推荐阅读
- javascript - SpeechRecognition:循环遍历一组问题;在问下一个问题之前等待每个“口头”回答
- c++ - 如何传递求解器工作空间大小
- php - 使用 axios 将多个变量传递给控制器 laravel
- postgresql - 将 where 子句与子查询结合使用,结果是包含在数组中的记录
- swift - 无法使用来自 readLine() 的字符串创建 NSExpression
- c++ - C++ 与 Visual Basic 中的同时性?
- android - 自定义文件扩展名无法打开
- python - 如何使用 statsmodel 解决以下错误?
- azure-web-app-service - 您无权查看此目录或页面 Azure 和 FTP(Filezilla 错误)
- java - 如何使用 spotify docker 客户端连接到主机上的 docker 守护进程