我想使用JavaScript计算给定字符串中每个字符的出现次数.
例如:
var str = "I want to count the number of occurances of each char in this string";
Run Code Online (Sandbox Code Playgroud)
输出应该是:
h = 4;
e = 4; // and so on
Run Code Online (Sandbox Code Playgroud)
我试着搜索谷歌,但没有找到任何答案.我希望实现这样的目标 ; 订单没关系.
小智 19
简短的答案,减少:
let s = 'hello';
var result = [...s].reduce((a, e) => { a[e] = a[e] ? a[e] + 1 : 1; return a }, {});
console.log(result); // {h: 1, e: 1, l: 2, o: 1}
Run Code Online (Sandbox Code Playgroud)
T.J*_*der 14
这在JavaScript(或支持地图的任何其他语言)中非常非常简单:
// The string
var str = "I want to count the number of occurances of each char in this string";
// A map (in JavaScript, an object) for the character=>count mappings
var counts = {};
// Misc vars
var ch, index, len, count;
// Loop through the string...
for (index = 0, len = str.length; index < len; ++index) {
// Get this character
ch = str.charAt(index); // Not all engines support [] on strings
// Get the count for it, if we have one; we'll get `undefined` if we
// don't know this character yet
count = counts[ch];
// If we have one, store that count plus one; if not, store one
// We can rely on `count` being falsey if we haven't seen it before,
// because we never store falsey numbers in the `counts` object.
counts[ch] = count ? count + 1 : 1;
}
Run Code Online (Sandbox Code Playgroud)
现在counts每个角色都有属性; 每个属性的值是计数.您可以输出以下内容:
for (ch in counts) {
console.log(ch + " count: " + counts[ch]);
}
Run Code Online (Sandbox Code Playgroud)
我迭代每个字符并将其与计数一起放入嵌套对象中。如果该字符已存在于对象中,我只需增加计数即可。这是 myObj 的样子:
myObj = {
char1 = { count : <some num> },
char2 = { count : <some num> },
....
}
Run Code Online (Sandbox Code Playgroud)
这是代码:
function countChar(str) {
let myObj= {};
for (let s of str) {
if ( myObj[s] ? myObj[s].count ++ : myObj[s] = { count : 1 } );
}
return myObj;
}
var charCount = countChar('abcceddd');
Run Code Online (Sandbox Code Playgroud)
小智 5
let str = "atul kumar srivastava";
let obj ={};
for(let s of str)if(!obj[s])obj[s] = 1;else obj[s] = obj[s] + 1;
console.log(obj)
Run Code Online (Sandbox Code Playgroud)
小智 5
您可以在 Javascript 中使用 ES6 中的地图。在我看来,提供了更干净、简洁的代码。这是我的做法
function countChrOccurence ('hello') {
let charMap = new Map();
const count = 0;
for (const key of str) {
charMap.set(key,count); // initialize every character with 0. this would make charMap to be 'h'=> 0, 'e' => 0, 'l' => 0,
}
for (const key of str) {
let count = charMap.get(key);
charMap.set(key, count + 1);
}
// 'h' => 1, 'e' => 1, 'l' => 2, 'o' => 1
for (const [key,value] of charMap) {
console.log(key,value);
}
// ['h',1],['e',1],['l',2],['o',1]
}
Run Code Online (Sandbox Code Playgroud)