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

前端 未结 5 1458
执念已碎
执念已碎 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
        });
    });
    

提交回复
热议问题