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 NaNas the total. I believe it may be the way I'm declaring the subtotalvariable 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
parseFloatand parseIntcan return NaNif the first character of the string cannot be converted to a number.
parseFloat如果字符串的第一个字符无法转换为数字,则parseInt可以返回NaN。
So, I would safeguard against it like this (NaNis a falsyvalue):
所以,我会像这样防止它(NaN是一个虚假的价值):
price = parseFloat(price) || 0;
qty = parseInt(qty, 10) || 0;
Arithmetic operations on numbers with the value NaNalmost always result in NaN(NaN + 5will result in NaN.) That means, if only oneof the input cannot be parsed by parseFloator parseInt, your current code would end up calculating NaNfor the subtotal.
对具有该值的数字进行算术运算NaN几乎总是导致NaN(NaN + 5将导致NaN。) 这意味着,如果只有一个输入不能被parseFloator解析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
radixargument to theparseIntfunction; - Do not use
classfor 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用于变量名:它是一个保留(未使用,但保留)关键字; - 不要期望小计完全准确,除非您以美分进行计算。

