[英]How do I return the sum of all values in an array?
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'.我对 javascript 非常陌生,并且在确定是否应该使用
return
或document.write
或两者来返回名为“amount”的数组中所有值的总和时遇到问题。 I am supposed to create a function names amountTotal().我应该创建一个函数名称 amountTotal()。
The purpose of which is to return the sum of all values in the amount
array.其目的是返回
amount
数组中所有值的总和。 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.然后我要声明一个名为
total
的变量,将其初始值设置为 0。然后创建一个 for 循环,循环遍历amount
数组中的所有值。
At each iteration of the loop, add the current value of the array item to the value of the total
variable.在循环的每次迭代中,将数组项的当前值与
total
变量的值相加。 Finally, after the loop is completed I need to return the value of the total
variable.最后,循环完成后,我需要返回
total
变量的值。 The largest array value is [34]
.最大的数组值为
[34]
。 This value will be written to a table called Summary
该值将被写入一个名为
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?我在正确的轨道上吗?
Return a value from function.从函数返回一个值。
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
}
function sumArray(arr){
var total = 0;
arr.forEach(function(element){
// 'element' in the parenthesis can be any name
total += element;
});
return total;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.