简体   繁体   English

计算字符串数组中的子字符串

[英]Count substrings in an array of strings

I would like to count the number of use of Mr and Miss in the array.我想计算数组中 Mr 和 Miss 的使用次数。

I'v started with one of them and been trying a couple of solutions.我从其中一个开始,并尝试了几种解决方案。

But I can't get my head around how to sum the counts of the whole array, like when I console.log it, it will print each one of them, not the sum of all Mr in the array?但是我不知道如何对整个数组的计数求和,就像当我 console.log 它时,它会打印每一个,而不是数组中所有 Mr 的总和?

const array = [
  "Hello Mr, Hello Miss",
  "Hello Mr, Hello Miss",
  "Hello Mr, Hello Miss",
  "Hello Mr, Hello Miss"
];
console.log(array);

array.forEach((object) => {
  var count = (object.match(/Miss/g) || []).length;
  console.log("Number:", count);
});
```

 const array = [ "Hello Mr, Hello Miss", "Hello Mr, Hello Miss", "Hello Mr, Hello Miss", "Hello Mr, Hello Miss" ]; console.log(array); const count = (array.join(' ').match(/Miss|Mr/g) || []).length; console.log(count);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM