get random item from javascript array repeatedly?(反复从javascript数组中获取随机项?)
问题描述
我正在制作一个 Discord.js 机器人,该机器人的功能之一是在用户键入!fact"时从 Javascript 事实数组中返回一个随机项.这个问题已经被其他用户问了很多,我使用了给他们的答案中的代码,但我遇到了一个问题:机器人卡在"一个事实上,并且不会每次都随机遍历列表输入!fact".这是我到目前为止的代码示例:
I'm making a Discord.js bot and one of the functions of the bot is to return a random item from a Javascript array of facts when a user types "!fact". This question has been asked a lot by other users and I've used code from answers given to them but I've run into one problem: the bot gets "stuck" on one fact and doesn't go through the list randomly every time "!fact" is typed. This is an example of the code I have so far:
var facts = [ "Fact 1", "Fact 2", "Fact 3", "Fact 4" ]
var fact = Math.floor(Math.random() * facts.length);
然后,让机器人发送消息:
And then, for the bot to send the message:
client.on('message', message => {
if (message.content === "!fact") {
message.channel.send(facts[fact]);
console.log('Message sent');
}
});
但这只会一遍又一遍地返回类似 Fact 1
的内容,无论!fact"被输入多少次.我怎样才能让它每次都改变?
But this would only return something like Fact 1
over and over, no matter how many times "!fact" is typed. How can I make it change every time?
推荐答案
您在启动时使用此行仅确定一次随机事实:
You're determining your random fact just once at startup using this line:
var fact = Math.floor(Math.random() * facts.length);
要在每次 if 条件评估为真时获得一个随机事实,您需要为其中的事实重新分配一个新的随机整数:
To get a random fact each time the if-condition evaluates to true you need to re-assign a new random integer to facts in there:
client.on('message', message => {
if (message.content === "!fact") {
fact = Math.floor(Math.random() * facts.length);
message.channel.send(facts[fact]);
console.log('Message sent');
}
});
这篇关于反复从javascript数组中获取随机项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:反复从javascript数组中获取随机项?


基础教程推荐
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- Bokeh Div文本对齐 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01