javascript - 匹配字符串到数组
问题描述
我有很长的数组,我想检查其他数组中的一个元素是否与第一个数组中的任何元素匹配。
let name;
let list = ["Kat", "Jane", "Jack"]; // for example
let input = ["Hey", "i'm", "Jack"];
if (input.forEach(el => el.match(list))) {
do.something();
name = ''; // get name somehow
}
但是上面的代码总是返回 null。
解决方案
forEach
返回undefined
,因此条件永远不会通过。此外,您似乎在滥用match
.
您可以改为使用find
和includes
let list = ["Kat", "Jane", "Jack"]; // for example
let input = ["Hey", "i'm", "Jack"];
let name = input.find(name => list.includes(name))
if (name) {
console.log(name)
}
基本上“在'输入'中找到'列表'包含该元素的第一个元素”
推荐阅读
- ruby - 在命令行中运行 Cucumber 脚本时未定义的步骤定义
- amazon-web-services - CA 证书没有 basicConstraints 扩展为 true
- string - PySpark:在文本和子集数据框中搜索子字符串
- java - 为什么堆内存与 Java 8 中的元空间一起上升?
- iis - 异常类型:ArgumentException 异常消息:fullName
- python - Python:为什么当我没有导入命令时这个命令起作用
- typescript - 使用没有模块的定义文件
- python - Python3 错误:pip 安装后没有名为 telebot 的模块
- python-3.x - 如何在 elasticsearc_dsl 中搜索 md5 字段
- scala - intellij 工作表中的主要方法不运行?