【问题标题】:counting characteres in string using object使用对象计算字符串中的字符
【发布时间】:2021-11-24 01:26:45
【问题描述】:

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

function maxChar(str) {

    let obj = {}   

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

当我使用字符串“Hello There!”运行函数时它返回:

{
   : 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)
}

返回


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

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

【问题讨论】:

  • 在您的第一个示例中,obj[char] = 1 将始终运行,即使您增加了值,将其重置为 1。您可以将其放入 else
  • 第一个版本需要else,因此它不会在递增后将计数重置为 1。

标签: javascript string object if-statement counting


【解决方案1】:

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

    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
        }
    } 

【讨论】:

    猜你喜欢
    • 2014-10-21
    • 1970-01-01
    • 2022-11-12
    • 1970-01-01
    • 2019-09-14
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多