我正在尝试使用 ++
运算符递增一个变量,但我一直得到 NaN
结果,我不确定为什么。这是我的代码:
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());
最佳答案
wordCounts["_"+ words[i]]
的值最初是 undefined
所以当你++ 它时,它给你 NaN。只需将您的代码更改为:
if (wordCounts["_" + words[i]]) {
wordCounts["_" + words[i]]++;
} else {
wordCounts["_" + words[i]] = 1;
}
关于javascript - 自增运算符返回 NaN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8306093/