3 回答

TA貢獻1834條經(jīng)驗 獲得超8個贊
在這里使用正則表達(dá)式是多余的 - 相反,.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'));

TA貢獻1898條經(jīng)驗 獲得超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));
或者甚至更通用的方法,您可以創(chuàng)建一個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));
添加回答
舉報