Get count of most repeated letter in a word

2019-06-24 05:16发布

I am trying to get the count of the most repeated letter in a word

function GreatestCount(str)
{
    var count = {}

    for (var i = 0 ; i<str.length;i++)
    {
        var char = str[i];
        count[char] = (count[char] || 0) + 1;

    }

     //get the largest number for the letter counts
    var max = 0;

    for (var c in count) {
        if (count[c] > max) max = count[c];
    }

    return max
}

can someone explain to me why

count[char] = (count[char] || 0) + 1;// this works

count[char] += 1 // this does not work 

5条回答
狗以群分
2楼-- · 2019-06-24 05:32

On first occurrence count[char] is undefined and undefined += 1 !== 1

查看更多
贪生不怕死
3楼-- · 2019-06-24 05:48

Initially, count is an empty object, so it doesn't have the char property. Therefore, count[char] returns undefined.

And undefined + 1 produces NaN.

Therefore, you must inititialize it to 0 in order to make it work properly.

†: count is not really an empty object because it inherits properties from Object.prototype. It would be problematic if a char property is defined there. I recommend using count = Object.create(null) instead.

查看更多
别忘想泡老子
4楼-- · 2019-06-24 05:50

You need to initialize your count[char] to zero before incrementing it.

查看更多
We Are One
5楼-- · 2019-06-24 05:53

Because

count[char] += 1

is equal to

count[char] = count[char] + 1

and the first time the code is run, count[char] is undefined so it's pretty much the same as

undefined + 1 // which is NaN

The working version circumvents this case by safely adding with 0 using || operator.

查看更多
Fickle 薄情
6楼-- · 2019-06-24 05:56

As other said your variable is not initialize in the beginning so count[char] +=1 is not working, but when you do (count[char] || 0) you actually tell them that you want to set 0 if the variable is "false". False could mean undefined, NaN, 0.

查看更多
登录 后发表回答