【问题标题】:Check if an array of strings contains a substring检查字符串数组是否包含子字符串
【发布时间】:2021-12-14 05:36:52
【问题描述】:

我有一个这样的数组:

array = ["123", "456", "#123"]

我想找到包含子字符串"#" 的元素。我尝试了array.includes("#")array.indexOf("#"),但没有成功。

如何检查此数组中的任何字符串是否包含子字符串"#"

【问题讨论】:

  • 试试array.some(x => x.includes(y))
  • 我觉得更像array.find(item => item.includes('#'))

标签: javascript arrays


【解决方案1】:

因为包含会将“#”与每个数组元素进行比较。

如果您想查找是否要准确获取元素,请尝试使用 somefind

var array = ["123", "456", "#123"];

var el = array.find(a =>a.includes("#"));

console.log(el)

【讨论】:

  • “some”方法对于这种情况非常有用
  • 这只发现第一次出现。我不想得到所有的发生
  • 让我们使用map 而不是find 来满足您的需求@shorif2000 var el = array.map(a => a.includes("#") ? a : false).filter(Boolean);
【解决方案2】:

这里似乎有多个问题,因为标题和帖子正文不同。您想知道数组是否有元素还是要获取元素本身?如果你想获取一个元素,你想要哪一个——第一次出现、最后一次出现还是所有出现的数组?

这篇文章旨在为未来的访问者提供资源,这些访问者可能不一定想要find(即返回左侧的第一个元素),如顶部答案所示。为了详细说明这个答案,在布尔上下文中不分青红皂白地将some 替换为find 存在一个问题——返回的元素可能是错误的,如

if ([5, 6, 0].find(e => e < 3)) { // fix: use `some` instead of `find`
  console.log("you might expect this to run");
}
else {
  console.log("but this actually runs " +
    "because the found element happens to be falsey");
}

请注意,e =&gt; e.includes("#") 可以替换为任何谓词,因此这在很大程度上是与问题无关的。


是否有任何元素与谓词匹配?

const array = ["123", "456", "#123"];
console.log(array.some(e => e.includes("#"))); // true
console.log(array.some(e => e.includes("foobar"))); // false

MDN: Array.prototype.some()

每个元素都匹配谓词吗?

const array = ["123", "456", "#123"];
console.log(array.every(e => e.includes("#"))); // false
console.log(array.every(e => /\d/.test(e))); // true

MDN: Array.prototype.every()

与谓词匹配的第一个元素是什么?

const array = ["123", "456", "#123", "456#"];
console.log(array.find(e => e.includes("#"))); // "#123"
console.log(array.find(e => e.includes("foobar"))); // undefined

MDN: Array.prototype.find()

与谓词匹配的第一个元素的索引是多少?

const array = ["123", "456", "#123", "456#"];
console.log(array.findIndex(e => e.includes("#"))); // 2
console.log(array.findIndex(e => e.includes("foobar"))); // -1

MDN: Array.prototype.findIndex()

与谓词匹配的所有元素是什么?

const array = ["123", "456", "#123", "456#"];
console.log(array.filter(e => e.includes("#"))); // ["#123", "456#"]
console.log(array.filter(e => e.includes("foobar"))); // []

MDN: Array.prototype.filter()

与谓词匹配的所有元素的索引是什么?

const filterIndices = (a, pred) => a.reduce((acc, e, i) => {
  pred(e, i, a) && acc.push(i);
  return acc;
}, []);

const array = ["123", "456", "#123", "456#"];
console.log(filterIndices(array, e => e.includes("#"))); // [2, 3]
console.log(filterIndices(array, e => e.includes("foobar"))); // []

MDN: Array.prototype.reduce()

与谓词匹配的最后一个元素是什么?

const findLast = (a, pred) => {
  for (let i = a.length - 1; i >= 0; i--) {
    if (pred(a[i], i, a)) {
      return a[i];
    }
  }
};

const array = ["123", "456", "#123", "456#"];
console.log(findLast(array, e => e.includes("#"))); // "456#"
console.log(findLast(array, e => e.includes("foobar"))); // undefined

与谓词匹配的最后一个元素的索引是多少?

const findLastIndex = (a, pred) => {
  for (let i = a.length - 1; i >= 0; i--) {
    if (pred(a[i], i, a)) {
      return i;
    }
  }

  return -1;
};

const array = ["123", "456", "#123", "456#"];
console.log(findLastIndex(array, e => e.includes("#"))); // 3
console.log(findLastIndex(array, e => e.includes("foobar"))); // -1

【讨论】:

    【解决方案3】:

    你可以使用join方法:

    array.join('').indexOf("#")
    

    【讨论】:

      【解决方案4】:

      使用Array.some:

      array.some((item) => item.includes('#'));
      

      它只是检查某些项目是否包含“#” - 可读且清晰。

      【讨论】:

        【解决方案5】:

        你可以使用filter()。

            var array = ["123", "456", "#123"];
        
            console.log(array.filter(function(item){
                var finder = '#';
                return eval('/'+finder+'/').test(item);
            }));
        

        通过传递一个函数,您可以过滤并返回与您要查找的内容相匹配的元素。

        在这个例子中,我使用了eval(),只是因为获取字符串使用RegExp,但是可以使用==操作符获取。

        【讨论】:

        • 为什么要评估? {}{}{{}
        • 使用new RegExp() 而不是eval,或者最好只使用includes。如果子字符串恰好有特殊的正则表达式字符,则正则表达式方法会中断,所以这个答案在几个层面上都被打破了。
        猜你喜欢
        • 2011-11-09
        • 2013-05-18
        • 1970-01-01
        • 2021-12-20
        • 2019-02-04
        • 2020-11-28
        • 2014-11-22
        • 2013-02-05
        • 1970-01-01
        相关资源
        最近更新 更多