我正在尝试检查字符串是否包含我存储在数组中的某些单词...但是我对javaScript有点陌生,所以我不完全知道如何检查Array中的所有元素...这里是一个例子:
const fruits = ["apple", "banana", "orange"]
上面的数组只是一个示例,因为我实际上正在检查是否有人在聊天中发送脏话。
if(message.content.includes(fruits)){executed code};
我的问题是什么,当我检查水果时,它什么也没做,但是当我检查数组中的特定元素时,fruits[0] //returns apple
它实际上会检查...所以我的问题/问题是如何检查字符串数组中的所有元素不只是苹果。
您对的使用includes
是错误的。
从MDN:
includes()方法确定数组的条目中是否包含某个值,并根据需要返回true或false。
arr.includes(valueToFind [,fromIndex])
const fruits = ["apple", "banana", "orange"];
const swearWord = "orange";
// execute is available
if (fruits.includes(swearWord))
console.log("Swear word exists.");
else
console.log("Swear word doesn't exist.");
反之,如果string包含数组的脏话:
const fruits = ["apple", "banana", "orange"];
const swearWord = "this contains a swear word. orange is the swear word";
// execute is available
if (checkForSwearWord())
console.log("Swear word exists.");
else
console.log("Swear word doesn't exist.");
function checkForSwearWord() {
for (const fruit of fruits)
if (swearWord.includes(fruit)) return true;
return false;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句