1

I am very new to javascript and am having a problem figuring out if I should use return or document.write or both to return the sum of all values in an array called 'amount'. I am supposed to create a function names amountTotal().

The purpose of which is to return the sum of all values in the amount array. Then I am to declare a variable named total, setting its initial value to 0. Then create a for loop that loops through all the values in the amount array.

At each iteration of the loop, add the current value of the array item to the value of the total variable. Finally, after the loop is completed I need to return the value of the total variable. The largest array value is [34]. This value will be written to a table called Summary

This is what I have written so far.

<script type="text/javascript">
    function amountTotal() {
        var total = 0;
        for (i = 0; i < 35; i++) {
            document.write("<td>" + i + "</td>")
        }
    }
</script>

Am I on the right track?

4

2 回答 2

4

从函数返回一个值。

function amountTotal(amount) {
        var total = 0;
        for (i = 0; i < amount.length; ++i) {
             total += amount[i]; // add each element in an array to total
        }
        return total;// return sum of elements in array
}
于 2013-09-10T14:23:12.483 回答
1
function sumArray(arr){
    var total = 0;
    arr.forEach(function(element){
        // 'element' in the parenthesis can be any name
        total += element;
    });
    return total;
}
于 2020-07-21T16:14:28.920 回答