反复从javascript数组中获取随机项目? [英] get random item from javascript array repeatedly?

查看:42
本文介绍了反复从javascript数组中获取随机项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制造一个Discord.js机器人,该机器人的功能之一是当用户键入!fact"时从事实的Javascript数组中返回一个随机项.其他用户已经问了很多这个问题,我使用了给出给他们的答案中的代码,但是我遇到了一个问题:该机器人被一个事实卡住",并且每次都不会随机访问该列表.输入!事实".这是到目前为止的代码示例:

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 "的内容.我怎样才能每次改变它?

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条件条件为true时获取随机事实,则需要为其中的事实重新分配一个新的随机整数:

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数组中获取随机项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆