【问题标题】:If the query value, or part of the query value, is in the array, return true如果查询值或查询值的一部分在数组中,则返回 true
【发布时间】:2018-07-22 09:31:37
【问题描述】:

我有一个包含 600 多个姓名(名字和姓氏)的员工名单。基于这个列表,我需要创建一个数组。如果搜索查询字符串是数组的一部分,我还需要一种基于搜索查询浏览此数组并返回 truefalse 的语法。搜索查询已在名为 query 的变量中捕获。

例子:

  1. 数组

    var employee = [ "John Smith", "Bob Hope", "Scott John", "Calum John" ];

  2. 如果查询值或查询值的一部分在数组employee中,返回true,否则返回false em>

例子:

  • 如果 query 等于 john smith,则返回 true
  • 如果 query 等于 bob,则返回 true
  • 如果 query 等于 SCOTT JOHN FINANCE DEPARTMENT,则等于 true
  • 如果 query 等于 health insurance,则等于 false

所以基本上,如果搜索查询包含任何名称,则返回 true

希望这已经足够清楚了。 JavaScript 不是我的首选,所以非常感谢我能得到的所有帮助。

最好, 约翰

【问题讨论】:

  • const isItThere = employee.includes(name); // outputs as true or false尝试使用它。
  • 只有在查询完全匹配时才有效。如果数组中是“John Smith”,如果查询只有“John”则返回false

标签: javascript arrays contains predicate


【解决方案1】:

您可以将array#somearray#includes 结合使用,方法是将您的查询转换为小写字母以及将员工姓名转换为小写字母。

employees.some(employee => employee.toLowerCase().includes(query.toLowerCase()) || query.toLowerCase().includes(employee.toLowerCase()))

var employees = [ "John Smith", "Bob Hope", "Scott John", "Calum John" ],
    queries = ['john smith', 'bob', 'SCOTT JOHN FINANCE DEPARTMENT', 'health insurance'],
    result = queries.map(query => employees.some(employee => employee.toLowerCase().includes(query.toLowerCase()) || query.toLowerCase().includes(employee.toLowerCase())));
console.log(result);

【讨论】:

  • 感谢您回答哈桑!它越来越接近我正在寻找的东西。但是,查询变量(称为“查询”)独立于这种语法,只需要以某种方式调用。另外,是否有可能在一个函数中使用 return 语句来捕获所有这些内容?
  • 你想如何传递查询,一个简单的字符串还是一个字符串数组?
  • 一个简单的字符串。查询本身存储在一个名为“查询”的变量中。如果查询字符串或查询字符串的一部分在数组“employee”中,则返回true,否则返回false。
  • employees.some(employee => employee.toLowerCase().includes(query.toLowerCase()) || query.toLowerCase().includes(employee.toLowerCase())) 将此语句包装在一个函数中,您将得到结果
  • 太棒了!非常感谢你帮助哈桑。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-04
  • 2018-05-02
  • 1970-01-01
  • 2018-01-04
  • 1970-01-01
相关资源
最近更新 更多