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数组中获取随机项?
基础教程推荐
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
