编码Discord Bot时OR逻辑处理器出现问题

时间:2020-09-09 07:19:21

标签: javascript discord discord.js

这是我当前的代码,我想知道我是否必须使用一堆“ else if”,或者是否可以使其紧凑。

if (message.content.toLowerCase().includes(`word`||`word2`||`word3`||`word4`||`wd`||`wd2`||`wd3`||`wd4`)){ 
          message.reply('don\'t swear in front of me!');
          message.delete({ timeout: 100 })

}})

问题在于仅测试了第一个字符串即单词。 当我将它们键入不一致时,其他所有字符串均无响应。

1 个答案:

答案 0 :(得分:0)

您有正确的主意,但使用的||运算符有误。 ||运算符检查左边的语句是否为false/null/undefined,如果是,则检查右边的语句。您定义它的方式('word'||'word2'||...),运算符采用left语句,在这种情况下为字符串'word',并检查是否为false/null/undefined而不是因为它是字符串。因此,它从不检查其他任何单词。

我认为您打算如何使用它,如下所示:

if (message.content.toLowerCase().includes(`word`) || 
    message.content.toLowerCase().includes(`word2`) ||
    message.content.toLowerCase().includes(`word3`) ||
    ...etc
){ 
    // Code here
}

从理论上讲,这是可行的,但是正如您所看到的那样,这还远远不够干净,并且不费吹灰之力就能变大和笨重。更好的方法是使用Array.some()函数,该函数为数组中的每个项目调用一个函数,并在一项通过该函数时返回true。看下面的例子:

// Define an array of all the words that need to be checked.
const arrayOfBadWords = ['word', 'word2', 'word3', ...];

if (arrayOfBadWords.some(word => message.content.toLowerCase().includes(word))) {
    message.reply('The message contains a blacklisted word.');
} else {
    message.reply('The message looks absolutely fine.');
}