增量运算符返回NaN

2022-08-14 00:00:00 nan increment javascript post-increment

我试图使用++运算符递增变量,但结果总是得到NaN,我不确定为什么。以下是我的代码:

var wordCounts = { };
var x = 0
var compare = "groove is in the heart";
        var words = compare.split(//);
        for(var i = 1; i < words.length; i++){
            if(words[i].length > 2){
                wordCounts["_" + words[i]]++;
            }
        }


alert(wordCounts.toSource());

解决方案

wordCounts["_" + words[i]]的值最初是undefined,所以当您++它时,它会给您NaN。只需将您的代码更改为:

if (wordCounts["_" + words[i]]) {
    wordCounts["_" + words[i]]++;
} else {
    wordCounts["_" + words[i]] = 1;
}

相关文章