admin管理员组

文章数量:1316835

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 

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 
Share Improve this question asked Aug 21, 2015 at 14:19 ComputernerdComputernerd 7,78221 gold badges70 silver badges98 bronze badges 1
  • @Oriol already answered your question, but i would like to help u abit more. u can store the max while inserting to the object, that will reduce the last 'for' there, saves 26 loops. in Addition, you need to use .ToLowerCase to prevent counting the same letter in different counters. for example 'a' and 'A' will act differently unless you do this. – Ori Refael Commented Aug 21, 2015 at 14:42
Add a ment  | 

5 Answers 5

Reset to default 7

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.

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 remend using count = Object.create(null) instead.

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

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

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.

本文标签: javascriptGet count of most repeated letter in a wordStack Overflow