为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

天涯尽头无女友 2021-10-21 17:05:29
我正在计算字符串中包含 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,我发现这种方式有点笨拙。有没有更好的计算字符串的解决方案?谢谢
查看完整描述

3 回答

?
MMMHUHU

TA贡献1834条经验 获得超8个赞

在这里使用正则表达式是多余的 - 相反,.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'));


查看完整回答
反对 回复 2021-10-21
?
汪汪一只猫

TA贡献1898条经验 获得超8个赞

最好使用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));


查看完整回答
反对 回复 2021-10-21
?
慕田峪4524236

TA贡献1875条经验 获得超5个赞

const v = 'aa';

new RegExp(v + '[^(' + v + ')]?$', 's')


查看完整回答
反对 回复 2021-10-21
  • 3 回答
  • 0 关注
  • 101 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信