This question already has answers here:
Sum of two numbers with prompt
                                
                                    (8个答案)
                                
                        
                        
                            Adding two numbers concatenates them instead of calculating the sum
                                
                                    (20个答案)
                                
                        
                2年前关闭。
            
        

我试图找到数组中元素的总和
我的输入是:1 2 3 4 5
输出应为:15
我收到的输出:012345

<html>
<head>
</head>
<body>
<script>
var numbers=[];
var sum=0;
for (var i=0;i<5;i++)
{
    numbers.push(prompt('Enter Your Numbers'));
    sum += numbers[i];
}
function getSumOfArray() {
    return  sum;
}
document.write("The Sum of Array: "+getSumOfArray()+"<br />");
</script>

</body>
</html>

最佳答案

通过调用parseFloat()将字符串输入转换为数字,应该可以解决此问题。



<html>
<head>
</head>
<body>
<script>
var numbers = [];
var sum = 0;
for (var i = 0; i < 5; i++)
{
    numbers.push(parseFloat(prompt('Enter Your Numbers')));
    sum += numbers[i];
}
function getSumOfArray() {
    return sum;
}
document.write("The Sum of Array: " + getSumOfArray() + "<br />");
</script>

</body>
</html>

关于javascript - js中数组的总和,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49502506/

10-12 17:58