我有一个函数可以显示各种下拉列表的数字总数。如果下拉列表之一设置为 #(起始值),则结果值显示为 NaN。
我想更改 NaN 在我的页面上的显示方式。我希望它读为“--”而不是“NaN”。
这是带有变量和 if/else 省略的函数:
function multiply() {
$('#total').text((((beds * perhour) + (addbath)) * discount ));
}
如何将文本设置为--
而不是NaN
?
一个简单的解决方法是利用 NaN 是一个虚假值这一事实
function multiply() {
$('#total').text(((((beds * perhour) + (addbath)) * discount)) || 0);//instead of 0 you can pass any default value here like an empty string
}
function multiply() {
var total = ((beds * perhour) + (addbath)) * discount;
$('#total').text(!isNan(total) ? total : '--');
}
您可以在 jquery 中使用 isNumeric 函数,
$.isNumeric(NaN); // false