首页 > 解决方案 > 匹配字符串到数组

问题描述

我有很长的数组,我想检查其他数组中的一个元素是否与第一个数组中的任何元素匹配。

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。

标签: javascriptnode.jsregexmatch

解决方案


forEach返回undefined,因此条件永远不会通过。此外,您似乎在滥用match.

您可以改为使用findincludes

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

基本上“在'输入'中找到'列表'包含该元素的第一个元素”


推荐阅读