我一直在尝试解决字符串中字符计数的难题,并找到以下代码。代码有效,但我无法理解替换部分:
function getCharCounts(s) {
var letters = {};
s.replace(/\S/g, function(s){
letters[s] = (isNaN(letters[s] ? 1 : letters[s]) + 1);
});
return letters;
}
console.log(getCharCounts('he111 144pressions'));
请有人向我解释代码或编写更简单的版本吗?
答案 0 :(得分:6)
function getCharCounts(s) {
// This variable will be visible from inner function.
var letters = {};
// For every character that is not a whitespace ('\S')
// call function with this character as a parameter.
s.replace(/\S/g, function(s){
// Store the count of letter 's' in 'letters' map.
// On example when s = 'C':
// 1. isNaN checks if letters[c] is defined.
// It'll be defined if this is not a first occurrence of this letter.
// 2a. If it's not the first occurrence, add 1 to the counter.
// 2b. If it's the first occurrence, assigns 1 as a value.
letters[s] = (isNaN(letters[s]) ? 1 : letters[s] + 1);
});
return letters;
}
注意: isNaN()中的括号错误。上述代码已得到纠正。
答案 1 :(得分:2)
这是一个更简单的例子:
function getCharCounts(s) {
var letters = {};
var is_not_whitespace = /\S/;
// Iterate through all the letters in the string
for (var i = 0; i < s.length; i++) {
// If the character is not whitespace
if (is_not_whitespace.test(s[i])) {
// If we have seen this letter before
if (s[i] in letters) {
// Increment the count of how many of this letter we have seen
letters[s[i]]++;
} else {
// Otherwise, set the count to 1
letters[s[i]] = 1;
}
}
}
// Return our stored counts
return letters;
}