1

Say for example I want the largest number out of an array of numbers.

var numbers = [54,34,76,33,87,12,76,92,44,93,23];

I want to be able to use Math.max() to find the largest number without using eval.

So, I want to be able to pass an array of parameters to a function. The array's length can change, so Math.max(numbers[0],numbers[1]...) won't work.

Is there any way I can do this?

Oliver
  • 1,576
  • 1
  • 17
  • 31

1 Answers1

2

You can use the .apply() method:

var max = Math.max.apply(Math, numbers);

The .apply() method is a property of Function.prototype and so is available on all function instances. Its first argument is used as the value of this in the function to be called, and the second argument should be an array that will be used as the list of parameter values.

In my example above I used Math as the value for this, because that's what this will be in a typical invocation of Math.max, but (on my installation of Firefox at least) Math.max.apply(null, numbers); works too.

Pointy
  • 405,095
  • 59
  • 585
  • 614