3

我一直在尝试解决计算字符串中字符的难题,并找到了以下代码。该代码有效,但我无法理解替换部分:

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'));​

有人可以向我解释一下代码还是写一个更简单的版本?

4

2 回答 2

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

于 2013-03-04T14:43:31.580 回答
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;
}
于 2013-03-04T14:47:21.713 回答