Javascript重新定义了Infinity,NaN或“".为0 [英] Javascript redefine Infinity, NaN, or "" as 0
问题描述
我有一个JavaScript计算器,可以接受用户输入,进行一些数学运算并将结果写入输入字段"#theResult"
I have a javascript calculator which accepts user input, does some math and writes the result to the input field "#theResult"
由于"#theResult"在键盘上更新,因此有时"#theResult"将返回Infinity,NaN或",直到填写完所有字段.在填写所有字段之前,我希望"#theResult"返回0.这是代码:
Since "#theResult" updates on keyup, there are times when "#theResult" will return Infinity, NaN, or "" until all of the fields are filled out. Until all of the fields are filled out, I want "#theResult" to return 0 instead. Here is the code:
if (theResult === Infinity || theResult === "" || theResult === NaN) {
theResult === 0;
}
$("#theResult").val(theResult);
完整代码为此处
在此先感谢您的帮助!
推荐答案
您已使用theResult === 0
,而应使用theResult = 0
.
===
用于比较.如果要更改变量的值,请使用赋值运算符=
.
The ===
is for comparisons. When you want to change the value of a variable, you use the assignment operator =
.
就像@zzzzBov所说的那样,最简单的方法是将整个内容替换为
Like @zzzzBov said, the simplest thing to do is replace the whole thing with
theResult = isFinite(theResult) && theResult || 0; // updated
这掩盖了NaN
的微妙之处;如果用户完成操作并且结果确实是NaN
,则表明0
并不正确.
That glosses over the subtleties of NaN
however; if the user is finished and the result really is NaN
, showing that as 0
is not really correct.
这篇关于Javascript重新定义了Infinity,NaN或“".为0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!