我在互联网上找不到我需要的东西,或者可能是我没有使用正确的词语,但这是我的问题。
我有一个字符串例如: 好的机器人,给我看看 Foo 程序的文档。
这是我的关键字:["bot","doc", "show", "Foo"]
我希望如果字符串包含 3 个或更多关键字,我的函数将返回一条消息,例如
我考虑过
var message = "Ok bot, show me the doc of the Foo program.";
var keywords = ["bot","doc","show","foo"];
if(keywords.indexOf(message) >=3 ){
console.log('ok I understand');
}
但它不起作用
有人可以帮我吗?
谢谢
最佳答案
您正在调用 indexOf
函数,该函数返回数组中的项目索引。在您的情况下,您正在检查数组关键字中的message
,这在逻辑上是错误的条件
您可以通过 Array#filter 过滤找到的关键字和 String#includes然后检查它们的长度。
var message = "Ok bot, show me the doc of the Foo program.";
var keywords = ["bot","doc","show","foo"];
var keywordsFound = keywords.filter(item => message.includes(item));
if(keywordsFound.length >= 3 ) {
console.log('ok I understand');
}
关于javascript - 检查字符串是否包含关键字数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47777545/