代码之家  ›  专栏  ›  技术社区  ›  CCCC

react-.include返回意外结果

  •  1
  • CCCC  · 技术社区  · 5 年前

    我有一个低于值的字符串数组

    const lists = ["EH-AA","EH-BB","EH-CC"]
    

    我尝试使用下面的代码,我希望此语句返回true。

    lists.includes('EH-')
    

    但它实际上返回false。

    2 回复  |  直到 5 年前
        1
  •  1
  •   Jayce444    5 年前

    includes 它会检查数组中的确切值。您需要遍历列表中的每个项,并检查该项是否包含该子字符串。你可以用 .some :

    lists.some(item => item.includes('EH-'))
    
        2
  •  1
  •   kind user Faly    5 年前

    参加 然后检查 包括 一串

    const lists = ['EH-AA', 'EH-BB', 'EH-CC'];
    
    const checkForStr = (arr, str) =>
       arr.join(',').includes(str);
    
    console.log(checkForStr(lists, 'EH-'));
    console.log(checkForStr(lists, 'random'));