Get count of most repeated letter in a word

与世无争的帅哥 提交于 2019-12-10 16:49:21

问题


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 

回答1:


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.




回答2:


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.




回答3:


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




回答4:


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




回答5:


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.



来源:https://stackoverflow.com/questions/32142700/get-count-of-most-repeated-letter-in-a-word

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!