【问题标题】:Discord BOT, select random values from an arrayDiscord BOT,从数组中选择随机值
【发布时间】:2020-11-18 11:25:21
【问题描述】:

我正在尝试构建自己的 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]);
                    }

I dont want this to happen

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

【问题讨论】:

    标签: javascript arrays bots discord.js


    【解决方案1】:

    您可以对数组进行洗牌,然后取出前几个元素。这是使用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);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-18
      • 2020-09-04
      • 2012-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-19
      • 2021-06-05
      相关资源
      最近更新 更多