2016-02-17 241 views
0

我最近遇到了這個javascript函數來計算某個字符出現在字符串中的次數。 我可以看到它使用.replace()方法替換任何非空白空間的正則表達式,但我不能完全理解它將被替換。javascript三元運算符來計算字符串中的字符

function Char_Counts(str1) { 
    var uchars = {}; 
    str1.replace(/\S/g, function(l) { 
     uchars[l] = (isNaN(uchars[l]) ? 1 : uchars[l] + 1); 
    }); 
    return uchars; 
} 
console.log(Char_Counts("This is a sample string")); 

任何人都可以請解釋參數「L」是正在傳遞什麼樣的匿名函數和什麼是三元運算符中發生的事情,我manged實現,因爲這同樣的效果,但對循環使用嵌套,但我甚至無法看到這甚至遍歷字符串字符。這是控制檯中的輸出,我只是想了解到底發生了什麼。

Object { T: 1, h: 1, i: 3, s: 4, a: 2, m: 1, p: 1, l: 1, e: 1, t: 1, 3 more… } 
+1

是字符串中的字符相匹配...自從你正在使用'\ S'這是每一個非空格字符 –

+0

三元檢查如果字符已經存在於對象中,如果是,則遞增計數器其他設置爲1 – Tushar

回答

0

那麼到底是怎麼回事的功能是本

function Char_Counts(str1) { 
    //Create an object where we will hold the letters and thier counts 
    var uchars = {}; 

    // Get all non space characters matched with /\S/g regex 
    str1.replace(/\S/g, function (l) { 

    // here l represents each character as the regex matches it 
    // so finally the ternary operator assings to the letter property of our map: if we find the letter for the first time isNaN will return true from isNan(undefined) and we will assing 1 otherwise we will increase the count by 1 
    uchars[l] = (isNaN(uchars[l]) ? 1 : uchars[l] + 1); 
    }); 
    return uchars; 
} 

所以對於字符串These Ones正則表達式將匹配任何非空格字符所以TheseOnes在運行一個例子,在功能上l會是T然後h然後e

uchars['T']undefined所以isNaN(undefined)給出true 所以我們設置uchars['T'] = 1;

如果第一個說法是正確的,否則返回:

後評估的表情從MDN

條件三元運算符返回?後的評價體現在哪裏? expr1:expr2

如果條件爲真,則運算符返回expr1的值; 否則,它返回expr2的值。

另一種方式做,這將與Array#reduce

function Char_Counts(str){ 
    return str.replace(/\s/g, "").split("").reduce(function(prev, current){ 
    if(!(current in prev)){ prev[current] = 1} else { prev[current]++} 
    return prev; 
    }, {}) 
} 
2

這樣做很不尋常。實際上這種模式更多地被使用。它得到uchars[l]0的真實值並添加一個。

uchars[l] = (uchars[l] || 0) + 1;