我有一个包含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);
}
最佳答案
您对“随机播放”的定义是不正确的...与其从数组中选择随机项目然后将它们从数组中剪接出来,何不使用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());
}
在尝试编写自己的改组算法之前,请三思而后行……比您或我聪明的人,以前对此已经一团糟。