繁体   English   中英

javascript三元运算符来计算字符串中的字符

[英]javascript ternary operator to count characters in a string

我最近遇到了这个javascript函数,用于计算某个字符在字符串中出现的次数。 我可以看到它使用.replace()方法替换了任何非空白的正则表达式,但我无法完全理解它所替换的内容。

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”是什么,以及三元运算符内部到底发生了什么。我设法达到与之相同的效果,但是使用嵌套的for循环,但是我什至不能了解如何遍历字符串字符。 这是控制台中的输出,我只想确切了解正在发生的事情。

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

这样做是不寻常的。 实际上,这种模式更常用。 它获得uchars[l]的真实值或0然后加1。

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

所以功能上是这样的

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;

三元运算符在?之后返回求值表达式 如果第一条语句为true,则在:情况下返回评估的表达式:

MDN

条件? expr1:expr2

如果条件为true,则运算符返回expr1的值;否则为false。 否则,它返回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;
  }, {})
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM