如何从字典中的数组中调用随机值? (不和谐机器人)

How to call a random value from an array in a dictionary? (Discord Bot)

我有字典,假设:

var array1 = ["value 1", "value 2", "value 3"];
var array2 = ["value 1", "value 2", "value 3"];

var dict = {"this":array1,"that":array2};

如果我选择了一个键,如何从字典中调用数组中的随机值?

例如

dict["this"] // Should return a random value from array rather than all values

我曾尝试使用 Math.random 来获取随机索引号,这是可行的,但是在使用它时,它总是 return 相同的值,这意味着随机数生成器使用因为索引只运行一次并且不更新,导致每次都从数组中给出相同的值,除非我重新启动代码。

var array1 = ["value 1", "value 2", "value 3"]; // array1
var array2 = ["value 1", "value 2", "value 3"]; // array2

var randthis = Math.floor(array1.length * Math.random()); // random index for array 1
var randthat = Math.floor(array2.length * Math.random()); // random index for array 2

var dict = {"this":this[randthis],"that":that[randthat]};

msg.client.send(dict[this])

我应该怎么做才能让随机索引每次都给我一个不同的索引?或者以不同的方式实现这一目标。 我知道我可以通过随机导入并使用 random.choice(dict[this])

在 Python 中实现这一点

更新: 我在服务器模块的不同模块中有字典,以便在同一模块中没有太多代码。所以我从 dictionary.js 导出字典并在 actualcode.js 中使用它(不要认为这很重要,但要说明它只是为了确保)

更新 2:

server.js:

const Discord = require("discord.js");
const client = new Discord.Client;
const cmd = require("./commands");

client.on("message", msg => {
  const prefix = '$'

  if (msg.author == client.user){
    return
  };

  if (msg.content.startsWith(prefix)){
    var command = msg.content.split(prefix).slice(1);
    msg.channel.send(cmd[command+"_cmd"]);
  }

});

commands.js:

var array1 = ["value 1", "value 2", "value 3"]
var array2 = ["value 1", "value 2", "value 3"]
var randindex = Math.floor(array1.length * Math.random())
var randindex2 = Math.floor(array2.length * Math.random())

var cmd = {"test_cmd":array1[randindex], "test2_cmd":array2[randindex2]}

module.exports = cmd

你每次得到相同结果的原因是 commands.js 只被解释一次,当你第一次将文件加载到 server.js.

"fix"的方法是在命令中导出一个函数,并在需要时执行该函数:

function execCmd() {
    var array1 = ["value1", "value 2", "value 3"]
    var randindex = Math.floor(array1.length * Math.random())

    return {"test_cmd":array1[randindex]}
}

module.exports = execCmd;

const Discord = require("discord.js");
const client = new Discord.Client;
const cmd = require("./commands");

client.on("message", msg => {
  const prefix = '$'

  if (msg.author == client.user){
    return
  };

  if (msg.content.startsWith(prefix)){
    var command = msg.content.split(prefix).slice(1);
    var rndDict = cmd();
    msg.channel.send(rndDict[command+"_cmd"]);
  }

});