如何从表单结果中删除 isNaN ?
我正在创建一个小计算器。其中部分功能允许您输入最多 4 个数字,但也可以只输入 1,2 或 3 个数字。我已经让代码正常工作,除了当我只输入 1、2 或 3 个数字时,我未输入的数字会得到 NaN 结果。
如何摆脱 NaN 结果?
我用于分割输入表单数据的 jQuery 是 -
var numbers = num4.split(" ");
var firstNumber = parseInt(margins[0], 10),
secondNumber = parseInt(margins[1], 10),
thirdNumber = parseInt(margins[2], 10),
fourthNumber = parseInt(margins[3], 10);
console.log(firstNumber, secondNumber, thirdNumber, fourthNumber);
var shorthand1 = parseInt (firstNumber, 10) * 1;
var shorthand2 = parseInt (secondNumber, 10) * 1;
var shorthand3 = parseInt (thirdNumber, 10) *1;
var shorthand4 = parseInt (fourthNumber, 10) *1;
并且我只是将
shorthand1 + shorthand2 + shorthand3 + shorthand4
结果显示在页面上的 div 中。
问题是,如果我输入“10 10 10”而不输入第四个数字,我会得到以下结果:
10 10 10 NaN
我可以检查 NaN 而不会处理该结果吗?
I'm creating a little calculator. Part of this will allow you to input upto 4 numbers but you could just have 1,2 or 3 as well. I've got the code working except for when I only enter 1, 2 or 3 numbers I get a NaN result for the numbers I haven't entered.
How do I get rid of the NaN result?
my jQuery for splitting the inputted form data is -
var numbers = num4.split(" ");
var firstNumber = parseInt(margins[0], 10),
secondNumber = parseInt(margins[1], 10),
thirdNumber = parseInt(margins[2], 10),
fourthNumber = parseInt(margins[3], 10);
console.log(firstNumber, secondNumber, thirdNumber, fourthNumber);
var shorthand1 = parseInt (firstNumber, 10) * 1;
var shorthand2 = parseInt (secondNumber, 10) * 1;
var shorthand3 = parseInt (thirdNumber, 10) *1;
var shorthand4 = parseInt (fourthNumber, 10) *1;
and I just have
shorthand1 + shorthand2 + shorthand3 + shorthand4
as a result displayed in a div on the page.
The issues is if I enter "10 10 10" and not enter a fourth number I get a result of
10 10 10 NaN
Can I check for NaN and not get that result processed?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用 Javascript
isNaN(value)
函数检查值是否为 NaN。You can check if a value is NaN by using the Javascript
isNaN(value)
function.你可以在js中检查isNaN()。
请注意,isNaN() 函数仅检查值的“数字性质”,而不检查该值是否是有限的。要检查数字是否有限,您应该使用 JavaScript 的 isFinite()。
You could check isNaN() in js.
Note that the isNaN() function only checks for the "numerical nature" of a value, not whether the value it is finite. To check if a number is finite, you should instead use JavaScript's isFinite().
isNaN()
函数确定某个值是否为非法数字 (Not-a-Number)。如果值为 NaN,则该函数返回 true,否则返回 false。
输出:
假
真实
真的
对于您的情况,您可以如下检查:
The
isNaN()
function determines whether a value is an illegal number (Not-a-Number).This function returns true if the value is NaN, and false if not.
Output:
false
true
true
For your case, you can check like below: