samedi 2 octobre 2021

counting characteres in string using object

I'm trying to count the characters in a string using an object. This is the function that I wrote:

function maxChar(str) {

    let obj = {}   

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

When I run the function with the string "Hello There!" it returns:

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

Which of course is not counting properly. If I change the if statement like this:

function maxChar(str) {

    let obj = {}   

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

It returns


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

Are not tboth functions supposed to do the same? why is this happening?

Aucun commentaire:

Enregistrer un commentaire