增量运算符返回 NaN
我尝试使用 ++
运算符递增变量,但结果总是得到 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());
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());
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您基本上所做的是
undefined++
这将导致...
NaN
尝试...
wordCounts["_" + Words[i]] = ( wordCounts["_" + Words[i]]++ || 1);
由于
NaN
是一个“falsey”值,因此 ||将回落至1。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.为了能够使用
++
运算符(它接受一个数字并将其加一),目标首先需要有一个数字。尝试检查对象是否已定义,如果未定义,则通过将其值设置为 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.
Something like:
您试图增加一个对象(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)?
wordCounts["_" + Words[i]]
的值最初是undefined
,因此当您对它进行 ++ 操作时,它会给出 NaN。只需将您的代码更改为:The value of
wordCounts["_" + words[i]]
is initiallyundefined
so when you ++ it, it gives you NaN. Just change your code to:尝试类似...
您正在尝试增加
undefined
,这会给您NaN
。Try something like...
You are trying to increment
undefined
which is giving youNaN
.