Javascript返回NaN [英] Javascript returning NaN
问题描述
每次客户输入数量时,我都会尝试显示小计。但是,当我循环输入时,我得到一个 NaN
作为总数。我相信这可能是我在我的脚本中声明小计
变量的方式,但我之前没有遇到过这个:
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:
$('.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);
});
推荐答案
parseFloat
和 parseInt
如果第一个字符可以返回 NaN
该字符串无法转换为数字。
parseFloat
and parseInt
can return NaN
if the first character of the string cannot be converted to a number.
因此,我会像这样保护它( NaN
是a falsy 值):
So, I would safeguard against it like this (NaN
is a falsy value):
price = parseFloat(price) || 0;
qty = parseInt(qty, 10) || 0;
对数字进行算术运算,其值 NaN
几乎总是导致 NaN
( NaN + 5
将导致 NaN
。)这意味着,如果输入的一个无法通过 parseFloat
或 parseInt $ c解析$ c>,您的当前代码最终会计算小计的
NaN
。
Arithmetic operations on numbers with the value NaN
almost always result in NaN
(NaN + 5
will result in NaN
.) That means, if only one of the input cannot be parsed by parseFloat
or parseInt
, your current code would end up calculating NaN
for the subtotal.
评论中已经提到过(主要是 Felix ),但我认为值得强调因为这些是重要的问题:
It's already been mentioned in the comments (by Felix mostly) but I think it's worth the emphasis as these are important concerns:
- 始终将
radix
参数传递给parseInt
function; - 不要对变量名使用
class
:它是保留的(未使用,但保留)关键字; - 不要指望小计 完全准确,除非你以美分计算。
- 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 perfectly accurate unless you do your calculations in cents.
这篇关于Javascript返回NaN的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!