Javascript 返回 NaN
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7264752/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript returning NaN
提问by csm232s
I'm attempting to display a subtotal each time a customer enters a quantity. However, when I loop through my inputs, I get a NaN
as the total. I believe it may be the way I'm declaring the subtotal
variable in my script, but I haven't come across this before:
每次客户输入数量时,我都试图显示小计。但是,当我遍历我的输入时,我得到 aNaN
作为总数。我相信这可能是我subtotal
在脚本中声明变量的方式,但我以前从未遇到过:
$('.item-qty input').bind('keyup', function(){
var subtotal = 0.0;
$('.item-qty input').each(function(){
var class = $(this).attr('id');
var qty = $(this).val();
var price = $('.'+class).html();
price = parseFloat(price);
qty = parseInt(qty);
subtotal = subtotal + (price * qty);
});
$('.subtotal input').val(subtotal);
});
回答by Bryan Menard
parseFloat
and parseInt
can return NaN
if the first character of the string cannot be converted to a number.
parseFloat
如果字符串的第一个字符无法转换为数字,则parseInt
可以返回NaN
。
So, I would safeguard against it like this (NaN
is a falsyvalue):
所以,我会像这样防止它(NaN
是一个虚假的价值):
price = parseFloat(price) || 0;
qty = parseInt(qty, 10) || 0;
Arithmetic operations on numbers with the value NaN
almost always result in NaN
(NaN + 5
will result in NaN
.) That means, if only oneof the input cannot be parsed by parseFloat
or parseInt
, your current code would end up calculating NaN
for the subtotal.
对具有该值的数字进行算术运算NaN
几乎总是导致NaN
(NaN + 5
将导致NaN
。) 这意味着,如果只有一个输入不能被parseFloat
or解析parseInt
,您当前的代码最终将计算NaN
小计。
It's already been mentioned in the comments (by Felixmostly) but I think it's worth the emphasis as these are important concerns:
评论中已经提到了(主要是Felix),但我认为值得强调,因为这些是重要的问题:
- Always pass the
radix
argument to theparseInt
function; - Do not use
class
for variable names: It's a reserved (not used, but reserved) keyword; - Don't expect the subtotal to be perfectlyaccurateunless you do your calculations in cents.
- 始终将
radix
参数传递给parseInt
函数; - 不要
class
用于变量名:它是一个保留(未使用,但保留)关键字; - 不要期望小计完全准确,除非您以美分进行计算。