Home > OS >  I am trying to write a function that takes n numbers of integer parameters and return the products o
I am trying to write a function that takes n numbers of integer parameters and return the products o

Time:10-21

Here is my implementation

function multiplyAll(a, b, c){
    return a*b*c
}

This is working, but imagine we have 10 arguments, or in a case whereby we don't even know the number of arguments that will be supplied? this is exactly what I want to achieve. Thanks

CodePudding user response:

A simple and "clean" way to do it is by using an array as parameter of the function. Like so :

function foo(args) {
  let res = 1;
  for(let i = 0; i < args.length; i  ){
    res = res * args[i];
  }
  return res;
}
console.log(foo([2,3,4]))
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

You can use arguments like:

function argumentsFunction(a,b,c,d){
  console.log(arguments); // array of arguments
}
argumentsFunction(1,2,3,4)
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Reference:

CodePudding user response:

In ES6 you can now use the spread operator in function parameters. You can use the following code to achieve your goal

function add(...numbers) {
  let total = 0;
  for (const number of numbers) { 
    total  = number;
   }
  return total;
}

CodePudding user response:

Just use the arguments keyword and the Array.reduce function from standard library.

function multiplyAll(){
  return Array.from(arguments).reduce((a,b) => a * b);
}
  • Related