javascript - 有人会解释这段计算字符的代码吗?

标签 javascript regex character

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

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/

相关文章:

javascript - Anythingslider 圆 Angular 问题

javascript - 如何调试 JavaScript 中的正则表达式?

Java 正则表达式 : Count words/phrases/wildcards in HTML document

javascript - 显示空行 jQuery dataTables

javascript - 有没有办法使用 querySelector 来获取打开的影子 dom

java - 查找字符在字符串中的位置

swift - 在 Swift 中获取字符串的第 n 个字符

c - 如何将十进制整数转换为单个十六进制字符? (C)

javascript - 我创建了一个关闭/打开按钮,但第一次使用它时,您需要单击两次

java - 在一大串随机字符中找到一串随机字符(可能有错误)