简体   繁体   English

编写一个函数,返回它接收到的每个参数的值的总和

[英]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;
    }
  1. Start with result being a number, not a string: var result = 0 .result开始是一个数字,而不是一个字符串: var result = 0
  2. If you're iterating through arguments , you may as well skip the named first argument altogether.如果您正在遍历arguments ,您也可以完全跳过命名的第一个参数。
  3. Start iterating from 0, not 1.从 0 开始迭代,而不是 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 接收参数并返回它而不进行任何修改的函数 - Function that receives a parameter and returns it with no modifications 编写一个函数来打印接受这个 wa 中的参数的总和: sum(2)(3) 并输出 5 - Write a function to print the sum which takes the parameter in this wa: sum(2)(3) and outputs 5 我需要编写一个 function “checkArray”,它接收一个随机数数组并返回大于 5 的数字之和 - I need to write a function “checkArray” which receives an array of random numbers and return the sum of the numbers bigger than 5 接收一个对象(参数)并返回一个数组 - Receives an object (parameter) and returns an array 编写一个函数sumRange,当给定两个整数FROM和TO时,该函数返回从FROM到TO的整数之和 - Write a function sumRange, which, when given two integers FROM and TO, returns the sum of integers from FROM to TO 如何编写一个名为“ add”的函数。 这样一来,一旦它收到2个参数,就返回2个值的总和 - how to write a single function named `add`. Such that once it has received 2 arguments, it returns the sum of the 2 values 接收并返回函数的javascript函数 - A javascript function that receives and returns functions 编写一个名为 strLetterCount 的 function,它接受一个字符串并返回一个新字符串,其中包含每个字母及其在字符串中的计数 - Write a function called strLetterCount which accepts a string and returns a new string with each letter and its count in the string 传递一个返回数组作为参数的函数 - Passing a function which returns array as a parameter 接收可选的 propertyName 作为参数并返回对象的该属性的值或完整对象的函数的类型 - Types for a function that receives an optional propertyName as parameter and returns either that property's value of an object or the full object
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM