我一直在尝试解决计算字符串中字符的难题,并找到了以下代码。代码有效,但我无法理解替换部分:
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'));
有人可以向我解释一下代码或者写一个更简单的版本吗?
最佳答案
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() 中的括号是错误的。上面的代码已更正。
关于javascript - 有人会解释这段计算字符的代码吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15204066/