第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

計算字符串的另一種方法出現(xiàn)在數(shù)組中

計算字符串的另一種方法出現(xiàn)在數(shù)組中

天涯盡頭無女友 2021-10-21 17:05:29
我正在計算字符串中包含 aaa出現(xiàn)在數(shù)組中的次數(shù)。我不認(rèn)為我的代碼有問題。像下面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);所以這個數(shù)字3是正確的。但是,接下來的工作是計算出現(xiàn)了多少次,然后看起來像   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);所以每次如果我想找到一個新字符串的編號,我必須創(chuàng)建一個新的let,我發(fā)現(xiàn)這種方式有點笨拙。有沒有更好的計算字符串的解決方案?謝謝
查看完整描述

3 回答

?
MMMHUHU

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'));


查看完整回答
反對 回復(fù) 2021-10-21
?
汪汪一只貓

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));


查看完整回答
反對 回復(fù) 2021-10-21
?
慕田峪4524236

TA貢獻1875條經(jīng)驗 獲得超5個贊

const v = 'aa';

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


查看完整回答
反對 回復(fù) 2021-10-21
  • 3 回答
  • 0 關(guān)注
  • 123 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號