获取数组中的所有元素(Javascript)

9

我想检查一个字符串是否包含我存储在数组中的特定单词...但是我刚接触JS,不太清楚如何检查数组中所有元素。

以下是一个示例:

const fruits = ["apple", "banana", "orange"]

我正在检查聊天记录中是否有人发送了脏话。

if(message.content.includes(fruits)){executed code}

然而我的问题是当我检查水果时,它什么都不做,但是当我检查数组中的特定元素,例如 fruits[0] //返回苹果 时,它会实际检查那个元素... 所以我的问题/疑问是如何检查字符串是否包含数组中所有元素,而不仅仅是苹果。


这个回答解决了你的问题吗?判断数组是否包含某个值 - Always Helping
请问 message.content 是什么?它是一个字符串还是一个数组?我有点感觉它可能是用户在帖子中发布的某些评论,您想查看您的数组中是否包含其中任何单词,对吗? - CrayonViolent
是的,抱歉,message.content 是一个字符串,在 discord.js 中。我已经添加了该标签,但忘记澄清了。 - PandaDev
8个回答

10

你使用 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.");

为了检查另一种情况,即字符串是否包含数组中的脏话:

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;
}


是的,然而...这适用于数组...我正在尝试检查一个字符串是否包含脏话,而不是数组...我想如果有必要,我可以在字符串上使用toarray方法,然后执行您建议的操作。 - PandaDev
@PandaDev 我已经更新了两种情况的代码。如果有帮助,请点赞 :) - Shravan Dhar
我已经点赞了,因为你之前的代码也是非常有帮助的见解。这实际上比我之前使用的要好得多...谢谢你,我会考虑将你的答案作为最佳答案...再次感谢! - PandaDev
不用谢。作为奖励,您可以在比较两个字符串时使用.toLowerCase() - Shravan Dhar
1
我知道...我已经在使用它,这样人们就不能在脏话上使用大写字母的技巧了。 - PandaDev
对于大型数组,使用Set可能比Array更快-https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Set - James McGuigan

3
你弄反了,你需要在数据数组上使用 .includes 来检查该数组是否包含你要查找的单词。

const fruits = ["apple", "banana", "orange"]
console.log(fruits.includes("banana"))
console.log(fruits.includes("something not in the array"))


我有一种隐隐的感觉,OP的message.content是许多任意文本,他们想要查看其中是否包含某个单词,而不是精确匹配或本身就是一个数组。 - CrayonViolent
谢谢,我最终发现大多数人建议的是正确的...问题在于当我应该检查消息中是否包含数组的任何内容时,我确实是在检查字符串是否为数组。 - PandaDev

3
我会在这里使用交集。如果您不知道什么是交集...
一个交集是两个数组共有的元素。
例如:
swearWords = ["f***", "s***"];
messageWords = ["I", "am", "angry...", "f***", "and", "s***"];
let intersection = messageWords.filter(x => swearWords.includes(x));
console.log(intersection) //-> ["f***", "s***"]

感谢您的输入...我将在代码中稍后使用它,但最终我使用了一种更简单的方法,通过检查字符串中的数组内容而不是数组中的字符串内容...换句话说,我使用了array.includes而不是string.includes方法。 - PandaDev

3

反转它:

if(fruits.includes(message.content)){executed code};

关于Array.includes的文档。你正在使用String.includes方法。或者,你也可以使用indexOf方法。


我会很快尝试一下,因为我相信我可能像你建议的那样把它弄反了。 - PandaDev
这最终成为了最好的一个,谢谢你在这方面的帮助,我知道数组有那个方法,只是不太确定如何使用,直到你指出来,再次感谢!!! - PandaDev

2

试一下这个。

fruits.forEach(fruit => {
    if (message.content.includes(fruit)) {
        console.log('true')
        return;
    }
    console.log('false')
})

希望这可以帮助到你。

是的,这个方法可行,但我最终使用了数组.includes方法而不是字符串.includes方法,这样做更容易一些...不过还是谢谢你的建议!!! - PandaDev
好的,我也尝试了这个方法,与我选择的答案相比,这个没有出现错误...另一个方法基本上必须将数组项作为字符串的第一部分,而这种方法几乎是完美无缺的。 - PandaDev

2

你可以尝试使用数组 some 方法

const fruits = ["apple", "banana", "orange"]
const containsFruit = fruit => message.content.includes(fruit);

if(fruits.some(containsFruit)) { executed code }

containsFruit 是一个函数,如果在 message.content 中发现水果,则返回 true。

如果数组中的任何项被发现包含在 message.content 中,fruits.some(containsFruit) 将为 true。


这确实非常有效,但最终我选择了使用array.includes而不是string.includes,并解决了我的问题...不过在再次询问数组之前,我将在未来参考这个答案,非常感谢!!! - PandaDev

1
另一种方法是使用正则表达式。对于大型消息字符串,这可能比在循环中调用.includes()更快,而数组需要每次循环遍历整个字符串。但是这应该经过测试。
let fruits = ["apple", "banana", "orange"]
let fruits_regex = fruits.map(f => f.replace(/(?=\W)/g, '\\')).join('|');  // escape any special chars
// fruits_regex == "apple|banana|orange"

let message = 'apple sauce with oranges';
let matches = [ ...message.matchAll(fruit_regex) ]
// [
//   ["apple",  index:  0, input: "apple sauce with oranges", groups: undefined]
//   ["orange", index: 17, input: "apple sauce with oranges", groups: undefined]
// ]


0
const fruits = ["apple", "banana", "orange"]
if(fruits.some(x => message.content.includes(x))){
  /* executed code */
};

好的答案应该包含解释而不仅仅是代码。请编辑并解释,否则您的答案可能会被删除。 - Scransom

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接