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
5 Answers
Reset to default 7Because
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
版权声明:本文标题:javascript - Get count of most repeated letter in a word - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742012739a2413194.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论