Javascript numbers concatenate instead of adding but typeof is number not string

前端 未结 5 1453
执念已碎
执念已碎 2021-01-02 04:49

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 calcul

相关标签:
5条回答
  • 2021-01-02 05:15

    Tidy up your code a bit and avoid repetition:

    DEMO

    $(document).ready(function() {
        $("#calculate").click(function(){   
            var inputs = $("input"), theResult = 0;  // `inputs` is the list of all input elements
    
            for(var i = 0;i < inputs.length; i++)  // iterate over all inputs
                // parse their value, in base 10, and add to the theResult
                theResult += parseInt(inputs[i].value, 10); 
    
            alert(theResult); // 42
        });
    });
    
    0 讨论(0)
  • 2021-01-02 05:17

    You're concatenating the strings with + and then you're converting that concatenated result to an int.

    You want to convert to an integer before you add. Something like:

    var theTerm = parseInt($("#theTerm").val(), 10);
    ...
    var theResult = theTerm + theRate + thePrice + theTax + theDown + theTrade;
    
    0 讨论(0)
  • 2021-01-02 05:24

    you have to use parseInt function of java script.

    for ex: var theTerm = parseInt($("#theTerm").val());

    demo

    0 讨论(0)
  • 2021-01-02 05:27

    Change line and apply parseInt to each obj as follow

    var theResult = parseInt(theTerm) + parseInt(theRate) + parseInt(thePrice) + parseInt(theTax) + parseInt(theDown) + parseInt(theTrade);
    
    0 讨论(0)
  • 2021-01-02 05:28

    Instead of using parseInt, you can multiply number by 1. Its much faster and easier method to covert datatype.

    $(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));
        });
    });
    

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

    0 讨论(0)
提交回复
热议问题