javascript - 检查字符串是否包含数组的任何元素
问题描述
假设我有一个字符串:
const subject = "This process is flawless"
我有一个数组:
const matchArray = ["process","procedure","job"]
我希望如果主题包含 matchArray 中的任何关键字,
if (subject matches any keyword of matchArray ){
console.log('true')
}
我的第一直觉是使用包含,但我不想将数组与字符串匹配,而是将字符串与数组匹配。
我仍在探索,如果有人可以指导我,那将非常有帮助。
编辑:我找到了这个灵魂,但有没有比这更好的解决方案
const subject = "This process is flawless"
const matchArray = ["process","procedure","job"]
const exists = matchArray.some(matchArray => subject.includes(matchArray))
if (exists) {
console.log("Yes");
// notify
}
解决方案
使用some()
const subject = "This process is flawless"
const matchArray = ["process", "procedure", "job"]
console.log(matchArray.some(i => subject.includes(i)))
推荐阅读
- angular - 如何在Angular中检测具有相同值@Input()的变化?
- ms-access - Store filtered employees in training record
- kubernetes - Are Kubernetes requests really guaranteed?
- google-bigquery - BigQuery 中的 IP 过滤 | BigQuery 的安全性
- c# - JSON-config 中的 NLog 默认包装器使用
- angular - Ng build with chunking without the --watch flag 与 nodemon 和 electron 结合使用
- sap-cloud-platform - SAP BTP CF Apps APIs 上的 DOS 攻击缓解/速率限制
- python - 如何使用滚动功能来预测基于简单移动平均线或其他策略的趋势
- visual-c++ - KLR 2 Baru.exe 中 0x00007FF610DE1904 处的未处理异常:0xC0000005:访问冲突读取位置 0x000000BE306C4F20
- node.js - 使用单独集合中的特定文档的引用创建新文档后,如何更新集合中的文档?