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?
CodePudding user response:
Your first version looks like this. I've added some comments:
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
}
That version will always reset the character count to 1. Even if it had just briefly incremented the count to 2, it will still reset it to 1 immediately after having done so.
One fix (that most closely matches your original code) could be:
for(let char of str){
if(obj[char]){
obj[char] = 1
} else {
obj[char] = 1
}
}