Discord BOT,从数组中选择随机值



我正在尝试构建我自己的Discord机器人,我希望它从我已经拥有的数组中发送一些随机的东西,但不希望它们相同(每次都应该不同(。例如,我的数组中有5个元素,我想用数组中的3个不同元素进行回复。

这是我目前的代码:

var question = ["answer1", "answer2", "answer3", "answer4", "answer5"];
var temparray = [];
for(i=0;i<3;i++){

for(j=0;j<domande.length;j++){
temparray[i] = domande[Math.floor(Math.random() * domande.length)];
temparray[j] = temparray[i];
if(!temparray[i] === temparray[j]){

}
}
console.log(temparray[i]);
}

我不希望这种情况发生

2是太多了,还是我错过了什么?

您可以打乱数组,然后获取前两个元素。下面是一个使用Fisher Yates Shuffle的例子。

var question = ["answer1", "answer2", "answer3", "answer4", "answer5"];
for(let i = question.length - 1; i > 0; i--){
let idx = Math.floor(Math.random() * (i + 1));//or Math.random() * (i + 1) | 0
let temp = question[idx];
question[idx] = question[i];
question[i] = temp;
}
let randomValues = question.slice(0, 3);
console.log(randomValues);

或者,可以使用析构函数赋值来方便交换元素。

var question = ["answer1", "answer2", "answer3", "answer4", "answer5"];
for(let i = question.length - 1; i > 0; i--){
let idx = Math.floor(Math.random() * (i + 1));//or Math.random() * (i + 1) | 0
[question[i], question[idx]] = [question[idx], question[i]];
}
let randomValues = question.slice(0, 3);
console.log(randomValues);

最新更新