2016-02-17 249 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;