javascript - 从数组中获取不包括先前选择的随机值

标签 javascript arrays loops random

我已经开始使用 Javascript 构建一个 super 基本的“常识测验”...但我正在努力想出一种有效的方法来获取不包括先前选择的问题的随机问题。

目前我所拥有的是一个名为 previous_questions 的数组,它存储先前选择的问题的索引,以及一个 while 循环,如果该数字已存在于“r”中,则继续生成“r”的随机值previous_questions 数组。

var r = Math.floor(Math.random() * questions.length);
while(previous_questions.indexOf(r) >= 0) {
    r = Math.floor(Math.random() * questions.length);
}

虽然目前这是有效的,但我无法想象这是一种有效的方法,并且当没有问题可供选择时可能会导致无限循环。执行此操作的更有效方法是什么?提前致谢!

最佳答案

实现此目的的一种方法是随机排列问题,而不是一次随机选择问题。

function shuffle(a) {
  for (let i = a.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [a[i], a[j]] = [a[j], a[i]];
  }
  return a;
}

let questions = ["a", "b", "c", "d", "e", "f"];

shuffle(questions); /* Shuffle the question array */

//Looping thru the shuffled questions
questions.forEach(q => {
    console.log(q);
});

随机播放功能已被使用 here

关于javascript - 从数组中获取不包括先前选择的随机值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48867211/

相关文章:

php - 哪个更快 : in_array() or a bunch of expressions in PHP?

javascript - 将值/日期数组列表减少到最近 x 天并添加缺失的天数

linux - 从 bash 循环中的文件中提取第 n 行

Python - 重新启动 for 循环的方法,类似于 "continue"for while 循环?

arrays - perl6 在循环遍历数组时修改数组的一般方法

javascript - 停止在jsp中将 "<"转换为 "&lt;"

javascript - 索引或大小为负,或大于允许值。

c++ - 指针数组的段错误

javascript - 主干点击事件未注册

javascript - 如何正确使用与加载音频有关的事件