如何计算特定字符在字符串中的出现次数 [英] How to count the number of times specific characters are in a string
问题描述
我正在尝试创建一个函数,以查看数组中的任何字符是否在字符串中,如果是,则多少个字符.
I am trying to create a function that looks to see if any of the characters in an array are in a string, and if so, how many.
我尝试计算每种模式,但是太多了.我尝试使用Python中"in"运算符的替代方法,但效果不佳
I have tried to calculate every pattern, but there is too much. I tried using the alternative to the "in" operator from Python, but that didn't work out as well
function calc_fit(element) {
var fitness_let = ["e", "l", "m", "n", "t"]
}
}
element
是字符串,而Fitness_let数组是我需要检查的东西数组,以查看它们是否在字符串中,如果存在,则检查多少.
The element
is the string, and the fitness_let array is the array of things that I need to check to see if they are in the string, and if so, how many.
推荐答案
您可以使用 map 和 filter 计数具有相同数组值的出现次数:
You can count occurrences with an identical value of an array using map and filter:
let str="I love JavaScript and Node.js ";
let arr=str.replace(/[^a-zA-Z]/g, '').split('');
const mapped = [...new Set(arr)].map(a => `${a} occurs ${arr.filter(a1 => a1 === a).length } time(s)`);
console.log(mapped);
这篇关于如何计算特定字符在字符串中的出现次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!