简体   繁体   中英

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? 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;
    }
  1. Start with result being a number, not a string: var result = 0 .
  2. If you're iterating through arguments , you may as well skip the named first argument altogether.
  3. Start iterating from 0, not 1.

 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM