使用对象计算字符串中的字符

counting characteres in string using object

我正在尝试使用对象计算字符串中的字符数。这是我写的函数:

function maxChar(str) {

    let obj = {}   

    for(let char of str){
        if(obj[char]){
            obj[char] += 1 
        }           
        obj[char] = 1            
    }  
    console.log(obj)
}

当我 运行 带有字符串“Hello There!”的函数时它 returns:

{
   : 1,
  !: 1,
  e: 1,
  H: 1,
  h: 1,
  l: 1,
  o: 1,
  r: 1,
  T: 1
}

这当然不算数。如果我像这样更改 if 语句:

function maxChar(str) {

    let obj = {}   

    for(let char of str){
        if(!obj[char]){
            obj[char] = 1           
        }           
        obj[char] += 1      
    }  
    console.log(obj)
}

它returns


{
   : 2,
  !: 2,
  e: 4,
  H: 2,
  h: 2,
  l: 3,
  o: 2,
  r: 2,
  T: 2
}

这两个函数不是应该做同样的事情吗?为什么会这样?

您的第一个版本如下所示。我添加了一些评论:

    for(let char of str){
        if(obj[char]){
            obj[char] += 1  // this happens only when the `if` condition is met
        }           
        obj[char] = 1 // this happens all the time, regardless of the `if` condition
    } 

该版本总是会将字符计数重置为 1。即使它只是将计数短暂地增加到 2,它仍然会在完成后立即将其重置为 1。

一个修复(最接近您的原始代码)可能是:

    for(let char of str){
        if(obj[char]){
            obj[char] += 1
        } else {
            obj[char] = 1
        }
    }