Javascript数字串联而不是添加,但typeof是数字而不是字符串 [英] Javascript numbers concatenate instead of adding but typeof is number not string

查看:61
本文介绍了Javascript数字串联而不是添加,但typeof是数字而不是字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是javaScript的新手.我正在此处

I am new to javaScript. I am building a calculator here

我将输入值存储在变量中,以便最终可以操纵结果以基于输入进行计算.现在,我只想将所有值加在一起.

I have stored the input values in variables so that I can eventually manipulate the results to perform calculations based on input. For now I just want all of the values to add together.

但是,它们是串联的,而不是添加的.我使用parseInt来防止javascript将数字视为字符串,而typeOf则表明它们是数字.

However, rather than adding, they are concatenating. I used parseInt to prevent javascript from viewing the numbers as strings, and typeOf reveals that they are numbers.

这是我的JavaScript:

Here is my 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));
});

}); 

和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>

推荐答案

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

Change line and apply parseInt to each obj as follow

var theResult = parseInt(theTerm) + parseInt(theRate) + parseInt(thePrice) + parseInt(theTax) + parseInt(theDown) + parseInt(theTrade);

这篇关于Javascript数字串联而不是添加,但typeof是数字而不是字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆