【问题标题】:javascript find parcial string text in array objectjavascript 在数组对象中查找部分字符串文本
【发布时间】:2022-07-06 04:03:36
【问题描述】:

示例: 如果我使用下面的代码,它适用于整个单词“gorilla”。

如何让它与“gor”或“illa”或“orill”一起使用...?

...(例如,相当于mysql中的“%gor%”之类的str)

const jungle = [
  { name: "frog", threat: 0 },
  { name: "monkey", threat: 5 },
  { name: "gorilla", threat: 8 },
  { name: "lion", threat: 10 }
];

const names = jungle.map(el => el.name);

// returns true
document.write(names.includes("gorilla"));

【问题讨论】:

    标签: javascript arrays


    【解决方案1】:

    使用filter 代替map

    const jungle = [
      { name: "frog", threat: 0 },
      { name: "monkey", threat: 5 },
      { name: "gorilla", threat: 8 },
      { name: "lion", threat: 10 }
    ];
    const names = jungle.filter(el => el.name.includes("go"));
    
    console.log(names)

    【讨论】:

      【解决方案2】:

      const jungle = [
        { name: "frog", threat: 0 },
        { name: "monkey", threat: 5 },
        { name: "gorilla", threat: 8 },
        { name: "lion", threat: 10 }
      ];
      const names = jungle.map(el => el.name);
      console.log(names.some((name) => "gorilla".includes(name))); // returns true

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-03-31
        • 1970-01-01
        • 2020-05-17
        • 1970-01-01
        • 1970-01-01
        • 2017-10-03
        • 2022-12-03
        相关资源
        最近更新 更多