Com*_*erd 4 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
}
Run Code Online (Sandbox Code Playgroud)
能有人向我解释原因吗?
count[char] = (count[char] || 0) + 1;// this works
count[char] += 1 // this does not work
Run Code Online (Sandbox Code Playgroud)
因为
count[char] += 1
Run Code Online (Sandbox Code Playgroud)
等于
count[char] = count[char] + 1
Run Code Online (Sandbox Code Playgroud)
并在第一时间代码运行,count[char]是undefined因此它几乎是一样的
undefined + 1 // which is NaN
Run Code Online (Sandbox Code Playgroud)
工作版本通过0使用||运算符安全地添加来绕过这种情况.
最初,count是一个空对象†,所以它没有char属性.因此,count[char]退货undefined.
并undefined + 1生产NaN.
因此,您必须初始化它0才能使其正常工作.
†:count实际上不是一个空对象,因为它继承了属性Object.prototype.如果在char那里定义了属性,那将是有问题的.我推荐使用count = Object.create(null).
| 归档时间: |
|
| 查看次数: |
224 次 |
| 最近记录: |