Use arguments [JavaScript]

[Programming questions] Use arguments

Popularity index: 24549 Time limit: C/C++ 2 seconds, other languages ​​4 seconds Space limit: C/C++ 256M, other languages ​​512M

The function useArguments can receive 1 or more parameters. Please implement the function useArguments to return the result of adding all the call parameters. The test parameters of this question are all Number type, no need to consider parameter conversion.
Example 1

Enter
1, 2, 3, 4

Output
10

Link: https://www.nowcoder.com/questionTerminal/df84fa320cbe49d3b4a17516974b1136?f=discussion
Source: Niuke

This question examines the use of arguments. Arguments can obtain the parameter group passed in by the function object, similar to an array. The number of parameters can be obtained by length, and the parameter at that position can be obtained by subscript. However, since arguments are not an array, it is Class array, there are other values ​​for normal parameters, so methods such as forEach cannot be used. This question first obtains the number of parameters through arguments.length, and then loops the sum to get the result.
code show as below:

function useArguments() {
    
    
  /*
   因为参数数量不定,可以先获取参数个数arguments.length
   然后循环求值
  */
  //声明一个变量保存最终结果
  var sum = 0;
  //循环求值
  for(var i = 0; i < arguments.length; i++){
    
    
      sum += arguments[i];
  }
  return sum;
 }

Guess you like

Origin blog.csdn.net/weixin_42345596/article/details/105060053