Home > Enterprise >  How to use Math.min() and Math.max() in a function with n arguments?
How to use Math.min() and Math.max() in a function with n arguments?

Time:12-23

I'm a beginner, and I'm trying to write a function to calculate the mean of the smallest and highest numbers in any given sequence of numbers. However, I haven't been able to insert the right command inside the parameters of the method. Can you guys help me?

Here's my code:

function midrange () {
let min = Math.min(arguments);
let max = Math.max(arguments);
let mean = (min   max) / 2;
  console.log("min:", min);
  console.log("max:", max);
return mean;
}

CodePudding user response:

I think you have to pass arguments Value in your Method. If it's not declared Globally

CodePudding user response:

function midrange (...arguments) {
let min = Math.min(...arguments);
let max = Math.max(...arguments);
let mean = (min   max) / 2;
  console.log("min:", min);
  console.log("max:", max);
  console.log(mean)
return mean;
}

midrange(1, 2, 4,7, 1, 2 ,3 ,5)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters?retiredLocale=uk

CodePudding user response:

You could use Spread syntax (...):

function midrange(...arguments) {
  const min = Math.min(...arguments);
  console.log(`min: ${min}`);
  const max = Math.max(...arguments);
  console.log(`max: ${max}`);
  return (min   max) / 2;
}

console.log(`midrange: ${midrange(1, 2, 3)}`);

  • Related