我正在使用js制作一个discord bot,但由于某些原因我无法通过for循环让机器人正确打印数组。代码在
之下const Discord = require('discord.js');
const getJSON = require('get-json')
const BotToken = "tokenid";
const TwitchClientID = "?client_id=clientid";
const TwitchAPI = "https://api.twitch.tv/kraken/streams/";
const bot = new Discord.Client();
var channelNames = ["channel1", "channel2", "channel3"];
bot.login('botloginid');
// !Live command that itterates through channelNames array and prints whether stream is currently live or not
bot.on("message", function(message) {
if (message.content === "!Live") {
for (var i = 0; i < channelNames.length; i++) {
getJSON(TwitchAPI+channelNames[i]+TwitchClientID, function(error, response) {
if (response.stream == null) {
message.reply(channelNames[i] + ' is currently not live');
} else {
message.reply(channelNames[i] + ' is currently live');
}
});
}
}
});
如果我输入message.reply('我是'+ i);在getJSON之前,它打印出0 1 2,这是正确的,但如果我把message.reply('我是'+ i);在getJSON之后,它打印出来,我是3,我是3,我是3.并且因为数组索引是0,1,2,返回3使得机器人显示'undefined is live / not live'而不是名字这个频道。我以前从未遇到过循环的问题,我无法理解为什么它会在getJSON下变为3,甚至不能迭代,因为循环肯定在工作。