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() 中的括号是错误的。上面的代码已更正。