2013-03-04 25 views
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'));​ 

會有人請解釋一下代碼給我或寫一個簡單的版本?

+0

閱讀:http://www.aivosto.com/vbtips/regex.html和http://stackoverflow.com/questions/2595392/what-does-the -question-mark-and-the-colon-ternary-operator-mean-in-objectiv – howderek 2013-03-04 14:42:51

+0

你確定它可行嗎?我試着用「abbc」得到這個:{「a」:2,「b」:1,「c」:2} http://jsbin.com/uzexer/1/edit – 2013-03-04 14:49:42

+1

@SteveWellens這是因爲isNaN行中的括號錯誤。 – jantimon 2013-03-04 14:50:34

回答

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()是錯誤的。上面的代碼已更正。

+2

如果OP想知道,replace中的第一個參數是一個正則表達式 - '/ \ S/g'。 '\ S'是一個正則表達式包裝器'/.../'中的非空格字符卡,帶有全局標誌'g'。 – Jesse 2013-03-04 14:58:01

+1

微妙:'isNaN'檢查字母[c]是否(或轉換成)'NaN'值。 'undefined'在轉換爲'Number'時轉換爲'NaN'。 'null'沒有。 – raina77ow 2013-03-04 15:03:52

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; 
} 
+0

我認爲原始函數比較簡單,因爲它使用方法調用作爲迭代器,在方法調用中定義正則表達式,並使用內聯條件語句。但我想這取決於你如何定義簡單。 – Jesse 2013-03-04 15:08:24

+2

@Jesse我想我會更簡單一些,因爲「少用一些初學者可能不知道的東西」。如果你不明白'.replace'的回調是什麼,或者你不明白三元操作,我的可能會更簡單。 – Xymostech 2013-03-04 22:44:24

+0

你完全正確。 – Jesse 2013-03-05 20:26:15