从 JS 数组中选择一个值并跳过它,直到显示所有值

Pick a value from JS array and skip it until all the values are displayed

我有一个包含 6 个值的数组。我是运行Math.random来洗牌。但是,它每次都会对数组进行洗牌并显示重复的值。我想打乱数组并获得 1 个唯一值。如果获取了所有其他值,则应从数组中删除该值。例如,如果一个数组有项目 1、2、3、4,并且在洗牌之后答案是 3。现在,我希望它排除 3 并从 1、2、4 中获取一个新值。


    const params = {
      icon_emoji: ':laughing:'
    };
    var members=['1','2','3','4','5','6','7'];
    var assignee = members[Math.floor(Math.random()*members.length)];

      bot.postMessageToChannel('general', `It's ${assignee}'s turn today!`, params);


}

function results() {


    const params = {
      icon_emoji: ':laughing:'
    };
    bot.postMessageToChannel('general', `Inside results`, params);


}

您可以使用 array.splice 函数从数组中删除一个项目

members.splice(Math.floor(Math.random()*members.length), 1);

注意:如果您想保留原始数组,我建议您创建一个临时数组并对该变量进行操作

您对 "shuffle" 的定义不正确...与其从数组中随机选取项目然后将它们拼接出数组,不如 actually shuffle (即以随机顺序重新排序)整个数组使用 Fisher-Yates shuffle 然后从该数组中弹出元素?

下面的随机播放函数转载自this answer:

function shuffle(array) {
  let currentIndex = array.length,
    temporaryValue, randomIndex;

  // While there remain elements to shuffle...
  while (0 !== currentIndex) {

    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    // And swap it with the current element.
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }

  return array;
}

const myArr = [1, 2, 3, 4, 5, 6];
shuffle(myArr);
while (myArr.length > 0) {
  console.log(myArr.pop());
}

在尝试编写您自己的洗牌算法之前请三思...比您或我更聪明的人以前在这方面搞砸了。