Javascript数字连接而不是添加但是typeof是数字而不是字符串

Hel*_*rld 10 javascript jquery

我是javaScript的新手.我在这里建一个计算器

我已将输入值存储在变量中,以便最终可以操作结果以根据输入执行计算.现在我只想将所有值加在一起.

但是,它们不是添加,而是连接在一起.我使用parseInt来阻止javascript将数字视为字符串,而typeOf显示它们是数字.

这是我的javascript:

$(document).ready(function() {

var theTerm = $("#theTerm").val();
var theRate = $("#theRate").val();
var thePrice = $("#thePrice").val();
var theTax = $("#theTax").val();
var theDown = $("#theDown").val();
var theTrade = $("#theTrade").val();
var theResult = parseInt(theTerm + theRate + thePrice + theTax + theDown + theTrade, 10);

$("#calculate").click(function(){
    alert(theResult);
    alert(typeof(theResult));
});

}); 
Run Code Online (Sandbox Code Playgroud)

和HTML:

<div id="calculator">
<span id="calculatorHeader">Monthly Payment Calculator</span>
<table style="margin:0 auto;">
    <tr>
    <td style="width:40px;">Term
        <input id="theTerm" size="5" value="7" name="term" style="width:35px" />
    </td>
    <td style="width:40px;">Rate(%)
        <input id="theRate" size="5" value="7" name="apr" style="width:35px" />
    </td>
    <td style="width:55px;">Price($)
        <input id="thePrice" size="6" maxlength="7" name="price" style="width:50px" value="7" />
    </td>
    <td style="width:40px;">Tax(%)
        <input id="theTax" size="4" maxlength="7" name="tax" style="width:35px" value="7" />
    </td>
    <td style="width:40px;">Down($)
        <input id="theDown" size="5" maxlength="7" name="downPmt" style="width:35px" value="7" />
    </td>
    <td style="width:40px;">Trade($)
        <input id="theTrade" size="5" maxlength="7" name="trade" style="width:35px" value="7" />
    </td>
    <td style="width:78px;">Est.Monthly Pmt
        <input id="theResult" size="7" maxlength="7" name="result" style="width:75px" value="0" />
    </td>
    </tr>
</table>
<button type="button" id="calculate">Add Boxes!</button>
</div>
Run Code Online (Sandbox Code Playgroud)

jok*_*ker 17

更改行并将parseInt应用于每个obj,如下所示

var theResult = parseInt(theTerm) + parseInt(theRate) + parseInt(thePrice) + parseInt(theTax) + parseInt(theDown) + parseInt(theTrade);
Run Code Online (Sandbox Code Playgroud)


Moh*_*dey 5

parseInt您可以将数字乘以而不是使用1.它更快更容易地隐藏数据类型.

$(document).ready(function () {
    var theTerm = $("#theTerm").val() * 1;
    var theRate = $("#theRate").val() * 1;
    var thePrice = $("#thePrice").val() * 1;
    var theTax = $("#theTax").val() * 1;
    var theDown = $("#theDown").val() * 1;
    var theTrade = $("#theTrade").val() * 1;
    var theResult = theTerm + theRate + thePrice + theTax + theDown + theTrade;

    $("#calculate").click(function () {
        alert(theResult);
        alert(typeof (theResult));
    });
});
Run Code Online (Sandbox Code Playgroud)

JSFiddle:http://jsfiddle.net/RqzPk/14/

  • 如果你想快速而紧凑,那么只需要输入一个`+`:`var theTerm = + $("#theTerm").val()`.就个人而言,我不认为这些"技巧"转换与显式数字转换一样可读(很容易错过开发人员的意图). (2认同)