Javascript 代码将自身循环三次并运行“;如果;声明两次及「;否则";一次声明

Javascript 代码将自身循环三次并运行“;如果;声明两次及「;否则";一次声明,javascript,node.js,discord,discord.js,Javascript,Node.js,Discord,Discord.js,我不知道为什么,但在消息中添加“questionwords”时,这段代码会重复3次,特别是它将运行else语句1和main if语句两次 bot.on('message', function(message) { const words = message.content.split(' '); if (words.includes('sans')) { var questionwords = ['can', 'is', 'was', ]; f

我不知道为什么,但在消息中添加“questionwords”时,这段代码会重复3次,特别是它将运行else语句1和main if语句两次

bot.on('message', function(message) {
    const words = message.content.split(' ');

    if (words.includes('sans')) {
        var questionwords = ['can', 'is', 'was', ];

        for (i in questionwords)
            if (!words.includes(questionwords[i])) {
                if (message.author.bot) return;
                var chance = Math.floor(Math.random() * 2);

                if (chance == 0) {
                    message.channel.send('<:annoying_sans:520355361425981440>');
                }

                if (chance == 1) {
                    message.channel.send('<:sans:519723756403425294>');
                }
            } else {
                var chance = Math.floor(Math.random() * 3);

                if (chance == 0) {
                    message.channel.send('Maybe.');
                }

                if (chance == 1) {
                    message.channel.send('Yes.');
                }

                if (chance == 2) {
                    message.channel.send('No.');
                }

            }

    }
});
bot.on('message',函数(message){
const words=message.content.split(“”);
if(单词.includes('sans')){
var questionwords=['can','is','was',];
因为(我用疑问的话)
如果(!words.includes(问题词[i])){
if(message.author.bot)返回;
var chance=Math.floor(Math.random()*2);
如果(机会==0){
message.channel.send(“”);
}
如果(机会==1){
message.channel.send(“”);
}
}否则{
var chance=Math.floor(Math.random()*3);
如果(机会==0){
message.channel.send('Maybe');
}
如果(机会==1){
message.channel.send('Yes');
}
如果(机会==2){
message.channel.send('No.);
}
}
}
});

在我看来,您似乎想知道
问题词
数组中的词是否在消息中。您已经知道如何使用
Array.includes()
检查单个单词,但多个单词更复杂

如果您只想知道单词数组中的任何单词是否与questionwords数组中的任何单词匹配,可以使用
array.some()

也许您想确保它们都在那里,请使用
Array.every()

可能您想知道有多少,或者您想获得匹配项(
Array.filter()
):


正如James在评论中所说,因为questionwords数组中有三个单词,所以for循环将运行三次。然后,它将为每个单词回复一次

但是,如果删除for循环并更改

if(!words.includes(问题词[i])

if(!words.includes(“can”| |“is”| |“was”))


您将得到相同的结果,而无需bot重复自身,因为它将搜索“can”或“is”或“was”,而不是“can”,然后搜索“is”,然后搜索“was”。

message.channel.send(…)
再次触发
bot.on(“message”,…)
。传入的
message
的值是多少,是字符串吗?questionwords数组中有3个元素,您在其上循环,因此if/else运行3次。
var wereAnyFound = words.some(word => questionwords.indexOf(word) > -1);
// true or false
var wereAllPresent = words.every(word => questionwords.indexOf(word) > -1);
// true or false
var matches = words.filter(word => questionwords.indexOf(word) > -1);
// an array of matches

var howMany = matches.length;
// number