【问题标题】:Check if a string exist in array检查数组中是否存在字符串
【发布时间】:2021-12-27 06:35:24
【问题描述】:

我有以下键 StudentMembers[1].active 但我需要检查以下数组中是否存在此键

const array= ["StudentMembers.Active","StudentMembers.InActive"]

如何从StudentMembers[1].active 中删除索引[1] 并检查数组中是否存在StudentMembers.Active

【问题讨论】:

    标签: javascript arrays typescript


    【解决方案1】:

    您可以使用正则表达式删除所有括号[<any>],如下所示:

    const key = "StudentMembers[1].active".replace(/\[.*\]/, '');
    console.log(key); // Return "StudentMembers.active"
    

    然后你可以使用.find() 来检查数组是否包含键

    const array= ["StudentMembers.Active","StudentMembers.InActive"];
    const hasKey = array.find(item => item.toLowerCase() == key.toLowerCase()) ? true : false;
    console.log(hasKey); // Return true
    

    强烈建议使用.toLowerCase(),这样它可以匹配任何类型的情况。

    示例:https://jsfiddle.net/fhkx9v3n/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-06
      • 2017-01-27
      • 2012-05-09
      • 1970-01-01
      • 1970-01-01
      • 2022-12-18
      相关资源
      最近更新 更多