获取一个单词中最重复的字母数

时间:2015-08-21 14:19:25

标签: javascript hashtable

我正在尝试用一个单词来计算最重复的字母

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
}

有人可以向我解释为什么

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

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

5 个答案:

答案 0 :(得分:7)

因为

count[char] += 1

等于

count[char] = count[char] + 1

并且第一次运行代码时,count[char]undefined,因此它与

几乎相同
undefined + 1 // which is NaN

通过使用0运算符安全地添加||,工作版本可以避免这种情况。

答案 1 :(得分:5)

最初,count是一个空对象,因此它没有char属性。因此,count[char]会返回undefined

undefined + 1生成NaN

因此,您必须将其初始化为0才能使其正常运行。

†:count实际上不是一个空对象,因为它继承了Object.prototype的属性。如果在那里定义了char属性,那将会有问题。我建议改为使用count = Object.create(null)

答案 2 :(得分:3)

您需要在递增之前将 count [char] 初始化为零。

答案 3 :(得分:2)

首次出现时LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); Locationer locationListener = new Locationer(); locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener); lat = **NEED YOUR HELP TO GET THIS VALUE** lon = **NEED YOUR HELP TO GET THIS VALUE** queryBooks(lat, lon); 未定义且count[char]

答案 4 :(得分:0)

正如其他人所说,你的变量在开始时没有初始化 所以count [char] + = 1不起作用,但是当你这样做时(count [char] || 0)你实际告诉他们如果变量为“false”你想要设置0。 False可能意味着未定义,NaN,0。