我正在尝试检查一个字符串是否包含我存储在数组中的某些单词......但是我是 JS 的新手,所以我不完全知道如何检查数组中的所有元素。
这是一个示例:
const fruits = ["apple", "banana", "orange"]
我实际上是在检查是否有人在聊天中发送脏话。if(message.content.includes(fruits)){executed code}
但是我的问题是当我检查水果时它会做任何事情,但是当我检查数组中的特定元素时,如 fruits[0] //returns apple
它实际上会检查...所以我的问题/问题是如何检查数组中所有元素的字符串,而不仅仅是苹果。
最佳答案
您对 includes
的使用情况是错的。
来自 MDN:
The includes() method determines whether an array includes a certain value among its entries, returning true or false as appropriate.
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.");
要检查其他方式,如果字符串包含数组的脏话:
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;
}
关于javascript - 获取数组中的所有元素(Javascript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62295644/