我对 javascript 非常陌生,并且无法确定是否应该使用 return
或 document.write
或两者来返回某个值中所有值的总和。名为“金额”的数组。我应该创建一个名为 amountTotal() 的函数。
其目的是返回amount
数组中所有值的总和。然后我要声明一个名为 total
的变量,并将其初始值设置为 0。然后创建一个 for 循环,循环遍历 amount
数组中的所有值。
在循环的每次迭代中,将数组项的当前值添加到 total
变量的值中。最后,循环完成后,我需要返回total变量的值。最大的数组值为[34]
。该值将被写入名为 Summary
这就是我到目前为止所写的内容。
<script type="text/javascript">
function amountTotal() {
var total = 0;
for (i = 0; i < 35; i++) {
document.write("<td>" + i + "</td>")
}
}
</script>
我走在正确的道路上吗?
最佳答案
从函数返回一个值。
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
}
关于javascript - 如何返回数组中所有值的总和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18721329/