计算字符串的另一种方法出现在数组中

我正在计算字符串中包含 aaa出现在数组中的次数。我不认为我的代码有问题。像下面


const regex_aa = /aa[^(aa)]?$/s;

let arr = [];

const sstr = ['aa', 'aaaa', 'cc', 'ccc', 'bbb', 'bbaa'];

sstr.filter(e => {

if (regex_aa.test(e)) {

  arr.push(e);

}

});


console.log(arr.length);


所以这个数字3是正确的。但是,接下来的工作是计算出现了多少次,然后看起来像


   const regex_aa = /aa[^(aa)]?$/s;

    const regex_bb = /bb[^(aa)]?$/s;

    let arr1 = [];

    let arr2 = [];


    const sstr = ['aa', 'aaaa', 'cc', 'ccc', 'bbb', 'bbaa'];

    sstr.filter(e => {

      if (regex_aa.test(e)) {

        arr1.push(e);

      }

      if (regex_bb.test(e)) {

        arr2.push(e);

      }

    });


    console.log(arr1.length, arr2.length);


所以每次如果我想找到一个新字符串的编号,我必须创建一个新的let,我发现这种方式有点笨拙。有没有更好的计算字符串的解决方案?谢谢


天涯尽头无女友
浏览 102回答 3
3回答

MMMHUHU

在这里使用正则表达式是多余的 - 相反,.reduce通过测试字符串是否在.includes您要查找的子字符串上迭代来计算:const countOccurrences = (arr, needle) => (  arr.reduce((a, haystack) => a + haystack.includes(needle), 0));console.log(countOccurrences(['aa', 'aaaa', 'cc', 'ccc', 'bbb', 'bbaa'], 'aa'));console.log(countOccurrences(['aa', 'aaaa', 'cc', 'ccc', 'bbb', 'bbaa'], 'bb'));

汪汪一只猫

最好使用Array.reduce,make is as a function。另外,有没有必要使用regex中,为了找到一个字符串中的子串,你可以使用String.indexOf该像这样的东西:const sstr = ['aa', 'aaaa', 'cc', 'ccc', 'bbb', 'bbaa'];function countAppearanceOf(needle, arr) {  return arr.reduce((count, item) => count + (item.indexOf(needle) > -1 ? 1 : 0), 0);}console.log(countAppearanceOf('aa', sstr));或者甚至更通用的方法,您可以创建一个predicate方法。const sstr = ['aa', 'aaaa', 'cc', 'ccc', 'bbb', 'bbaa'];function generalCountAppearanceOf(needle, arr, predicate) {  return arr.reduce((count, item) => count + (predicate(needle, item) ? 1 : 0), 0);}function generateCounterByPredicate(predicate) {  return (needle, arr) => generalCountAppearanceOf(needle, arr, predicate);}function predicatWithIndexOf(needle, item) {  return item.indexOf(needle) > -1;}function predicatWithRegex(needle, item) {  return /bb(aa)+/.test(item);}const countAppearanceOfWithIndexOf = generateCounterByPredicate(predicatWithIndexOf);const countAppearanceOfWithRegex = generateCounterByPredicate(predicatWithRegex);console.log(countAppearanceOfWithIndexOf('aa', sstr));console.log(countAppearanceOfWithRegex('aa', sstr));

慕田峪4524236

const v = 'aa';new RegExp(v + '[^(' + v + ')]?$', 's')
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript