The increment operator returns NaN

I am trying to increment a variable using an operator ++, but as a result I get NaN, 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());
+5
source share
5 answers

The value is wordCounts["_" + words[i]]original 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;
}
+10
source

Try something like ...

var key = "_" + words[i];

if (wordCounts[key]) {
    wordCounts[key]++
} else {
    wordCounts[key] = 1;
}

You are trying to increase undefined, which gives you NaN.

+2
source

++ ( ), .

, , , 1.

if ('undefined' === typeof wordCounts["_" + words[i]]) {
            wordCounts["_" + words[i]] = 0;
}

Sort of:

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 ) );
+1
source

Basically you do

undefined++

Which will lead to ...

NaN

Try ...

wordCounts["_" + words[i]] = (wordCounts["_" + words[i]]++ || 1);

Since it NaNis a “false” value, then || will fall to 1.

+1
source

You are trying to increase the object (wordCounts [] ++), it is not a number, therefore it cannot be increased, therefore you get this error. What are you really trying to do (in plain English)?

0
source

All Articles