我正在尝试计算单词中重复次数最多的字母的数量
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
Because
count[char] += 1
等于
count[char] = count[char] + 1
第一次运行代码时,count[char]
is undefined
所以它几乎与
undefined + 1 // which is NaN
工作版本通过安全地添加来规避这种情况0
using ||
操作员。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)