首页 > 解决方案 > 我需要从字符串值表中返回一个随机字符串

问题描述

我要编写的代码非常简单,我希望 Discord 机器人对“调查说?”命令以“是”或“否”响应。由于某种原因,它表示响应的值不能为空。

这是代码:

} else if (message.content == "survey says?") {
    var Options = {
        [1] : "Yes",
        [2] : "No"
    };

    var Num = ( Math.random() * 1 + 2); // will return either 1 or 2

    console.log(Num);

    var Option = Options[Num];

    message.channel.send(Option);
}

标签: javascriptdiscord.js

解决方案


问题是(Math.random() * 1 + 2)不会返回 1 或 2。它将返回一个介于 2 和 3 之间的数字。这意味着,Option将是未定义的,您尝试将其作为消息发送,这是不允许的。

如果你想要一个选项数组的随机元素(不知道你为什么使用一个对象Options),你可以使用这样的辅助函数:

function random(arr) {
  return arr[Math.floor(Math.random() * arr.length)]
}

const option = random(['yes', 'no'])

console.log(option)

你可以像这样简化你的代码:

function random(arr) {
  return arr[Math.floor(Math.random() * arr.length)]
}

// ...

} else if (message.content === 'survey says?') {
  const options = ['Yes', 'No']
  const option = random(options)

  message.channel.send(option)
}

推荐阅读