問題描述
我正在制作一個 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數組中獲取隨機項?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!