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 に答える