I am trying to increment a variable using the ++
operator but I keep getting NaN
as a result and I'm not sure why. Here is my code:
var wordCounts = { };
var x = 0
var compare = "groove is in the heart";
var words = compare.split(/\b/);
for(var i = 1; i < words.length; i++){
if(words[i].length > 2){
wordCounts["_" + words[i]]++;
}
}
alert(wordCounts.toSource());
I am trying to increment a variable using the ++
operator but I keep getting NaN
as a result and I'm not sure why. Here is my code:
var wordCounts = { };
var x = 0
var compare = "groove is in the heart";
var words = compare.split(/\b/);
for(var i = 1; i < words.length; i++){
if(words[i].length > 2){
wordCounts["_" + words[i]]++;
}
}
alert(wordCounts.toSource());
Share
Improve this question
edited Jun 23, 2014 at 18:33
laurent
90.8k82 gold badges309 silver badges441 bronze badges
asked Nov 29, 2011 at 5:03
mcgrailmmcgrailm
17.6k22 gold badges85 silver badges131 bronze badges
2
|
5 Answers
Reset to default 10The value of wordCounts["_" + words[i]]
is initially undefined
so when you ++ it, it gives you NaN. Just change your code to:
if (wordCounts["_" + words[i]]) {
wordCounts["_" + words[i]]++;
} else {
wordCounts["_" + words[i]] = 1;
}
Try something like...
var key = "_" + words[i];
if (wordCounts[key]) {
wordCounts[key]++
} else {
wordCounts[key] = 1;
}
You are trying to increment undefined
which is giving you NaN
.
What you're basically doing is
undefined++
Which will result in...
NaN
Try...
wordCounts["_" + words[i]] = (wordCounts["_" + words[i]]++ || 1);
Since NaN
is a "falsey" value the || will fall back to 1.
To be able to use the ++
operator (which takes a number and increments it by one) the target needs to have a number first.
Attempt a check to see if the object is defined, and if not initialize it by setting it's value to 1.
if ('undefined' === typeof wordCounts["_" + words[i]]) {
wordCounts["_" + words[i]] = 0;
}
Something like:
var wordCounts = {};
var x = 0
var compare = "groove is in the heart";
var words = compare.split(/\b/);
for (var i = 1; i < words.length; i++) {
if ('undefined' === typeof wordCounts["_" + words[i]]) {
wordCounts["_" + words[i]] = 0;
}
if (words[i].length > 2) {
wordCounts["_" + words[i]]++;
}
}
alert( JSON.stringify( wordCounts ) );
You're trying to increment an object (wordCounts[]++) it's not a number so it can't be incremented, which is why you're getting that error. What are you actually trying to do (in plain English)?
words
is 0, not 1. Also, should not "I" and "a" count as words? You can change the regexp so as to filter out the non-word characters, thus removing the need for thewords[i].length > 2
check. See if you can figure how. – outis Commented Nov 29, 2011 at 5:06