如何使Javascript NaN和ParseInt等于零

How to make Javascript NaN and ParseInt to equal Zero

本文关键字:ParseInt 等于零 NaN 何使 Javascript      更新时间:2023-09-26

我正在尝试将我的空值和 NaN 值设置为尽可能简洁的数量 0,当我环顾网站时,这是我最接近那个点,但它没有用?谁能告诉我如何解决这个问题,以及它是使用 ParseInt 还是这个等式?谢谢

下面是一个JSFiddle:http://jsfiddle.net/446nb2zj/

<!DOCTYPE html>
<html>
<head>
<title>Project</title>
<style type=text/css>
.inbox
{ width=30px; text-align: right; border: 2px solid black; }
.align
{ text-align: right }
</style>
<script type="text/javascript">
    function compute()
{
var a = form1.inputA.value;
a = parseFloat(a);
var b = form1.inputB.value;
b = parseFloat(b);
var c = form1.inputC.value;
c = parseFloat(c);
var d = a + b + c;
form1.quantity.value = d.toFixed(2);
var e = a * 5.49;
form1.sumA.value = e.toFixed(2);
var f = b * 7.49;
form1.sumB.value = f.toFixed(2);
var g = c * 6.49;
form1.sumC.value = g.toFixed(2);
var h = e + f + g;
form1.total.value = h.toFixed(2);
var i = h * .06;
form1.tax.value = i.toFixed(2);
var j = i + h;
form1.sub.value = j.toFixed(2);
}
a = a || 0; 
}
function pageInit()
  {
    form1.inputA.focus();
 }

</script>
</head>
<body onload="pageInit();">
<form id="form1">
<table border="2" >
<tr><th colspan="4">Sample Order Form</th></tr>
<tr><th>Quantity</th><th>item</th><th>Unit Price</th><th>Totals</th></tr>
<tr><th><input tabindex="1" class="inbox" type="text" id="inputA" /></th><th>Apples</th>
<td>$5.49</td>
<th><input class="inbox" type="text" id="sumA" readonly="readonly" /></th></tr>
<tr><th><input tabindex="2"  
class="inbox" type="text" id="inputB" /></th><th>Pears</th><td>$7.49</td>
<th><input class="inbox" type="text" id="sumB" readonly="readonly" /></th></tr>
<tr><th><input tabindex="3" class="inbox" 
type="text" id="inputC"/></th><th>Grapes</th>    <td>$6.49</td>
<th><input class="inbox" type="text" id="sumC" readonly="readonly" /></th></tr>
<tr><th><input class="inbox" type="text" id="quantity" readonly="readonly" /></th>
<th class="align" colspan="2">Subtotal</th>
<th><input class="inbox" type="text" id="total" readonly="readonly" /></th></tr>
<tr><th class="align" colspan="3">Tax@6%</th>
<th><input class="inbox" type="text" id="tax" readonly="readonly" /></tr>
<tr><th><input tabindex="4" type="button" value="Compute" onclick="compute();" /></th>
<th class="align" colspan="2">Total</th>
<th><input class="inbox" type="text" id="sub" readonly="readonly" /></th></tr>
</table>
</form>
</body>
</html>

你可以简单地选择||运算符,任何未定义或NaN将设置为0

var a = parseInt('a') || 0;
var b = '' || 0;
console.log(a); // 0
console.log(b); // 0

据我从您的代码中看到,您似乎也对许多}(其中您有一个 = a || 0)

对于其余部分,您可以直接使用 XOR 运算符从输入表单中获取值