我想创建一个长度取决于用户输入的数组,然后尝试找到数组中所有数字的总和

I wanted to create an array with length depending on the users input and then tried to find the sum of all the numbers in the array

<!DOCTYPE html>
<html>
    <body>
        <script>
            var cases=prompt("number of ingredients");
            var i=0;
            var a=[];
            while (i<cases){
                i=i+1;
                var cost=prompt("cost of this ingredient");
                a.push(cost);
            }
            alert(a);
            var t=a.length;
            var sum=0;
            var j=0;
            while (j<t-1){
                var sum=sum+a[j];
                j=j+1;
            }
            alert(sum);
        </script>
    </body>
</html>

想要根据 'cases' 中的用户输入创建一个数组。然后尝试找到数组 'a' 中所有数字的总和。但它没有给我答案。怎么了?感谢帮助。

您应该将输入解析为整数,否则将被视为字符串。您还需要节点两次声明 sum 变量。也不需要变量 t。

<!DOCTYPE html>
<html>
<body>
    <script>
        var cases=prompt("Number of ingredients");
        var i = 0;
        var a = [];
        while (i < cases){
        var cost = prompt("Cost of this ingredient");
        a[i] = parseInt(cost);
            i = i + 1;
        }
        var sum=0;
        var j=0;
        while (j < a.length){
            sum=sum+a[j];
            j=j+1;
        }
        alert(sum);
    </script>
</body>

优化版本:

var cases = parseInt(prompt("number of ingredients")), a = [], cost = 0;
while (cases--) {
  var cost = prompt("cost of this ingredient");
  a.push(parseInt(cost,10));
}
alert(a);

var len = a.length, sum = 0;
while (len--) {
  sum += a[len];
}
alert(sum);