3 回答
![?](http://img1.sycdn.imooc.com/54584ed2000152a202200220-100-100.jpg)
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'));
![?](http://img1.sycdn.imooc.com/5458506b0001de5502200220-100-100.jpg)
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));
添加回答
举报