[英]Write a function which returns the sum of the values for each parameter it receives
I want the result to be the sum of every number, but instead, it only sums the first number with the rest.我希望结果是每个数字的总和,但相反,它只将第一个数字与其余数字相加。 For example if the parameter were : 1,2,3,4,5 it should come out with 15 but instead, it became 3456. Where did i go wrong?例如,如果参数是:1,2,3,4,5,它应该是 15,但它变成了 3456。我哪里出错了? Thank u guys, im new to this and thing were really complicated :((谢谢你们,我是新手,事情真的很复杂:((
function func1(sum) {
var result = '';
var i;
for (i = 1; i < arguments.length; i++) {
result += arguments[i] + sum;
}
return result;
}
result
being a number, not a string: var result = 0
.从result
开始是一个数字,而不是一个字符串: var result = 0
。arguments
, you may as well skip the named first argument altogether.如果您正在遍历arguments
,您也可以完全跳过命名的第一个参数。 function func1() { var result = 0; var i; for (i = 0; i < arguments.length; i++) { result += arguments[i]; } return result; } console.log(func1(1, 2, 3, 4, 5));
This should work这应该工作
function sum(value) { let result = 0; for(let i =0; i < value.length; i++) { result +=value[i]; } return result } let arry = [1,2,3,4,5] console.log(sum(arry)) //15
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.