javascript - 我需要从字符串值表中返回一个随机字符串
问题描述
我要编写的代码非常简单,我希望 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);
}
解决方案
问题是(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)
}
推荐阅读
- docker - docker 容器可以获取有关用于创建它的图像的信息吗?
- java - 从另一个项目创建 docker 映像
- spring-webflux - Spring WebClient GET 请求失败并显示“永久移动。重定向到”
- c++ - 有符号整数溢出未定义行为
- flutter - 将颤振小部件转为灰度
- c++ - 关于阴影类型定义的警告
- xml - 如何在响应模式中添加另一个根元素
- python - 面临执行 python 包的问题
- android - 错误:BottomNavigationView 支持的最大项目数为 5,删除项目并添加新项目后
- amazon-web-services - EKS 上的 AWS NLB 粘性会话