这是我当前的代码,我想知道我是否必须使用一堆“ 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 })
}})
问题在于仅测试了第一个字符串即单词。 当我将它们键入不一致时,其他所有字符串均无响应。
答案 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.');
}