Question about Math.min()

Y

Yansky

Hi, just a quick question about the Math.min() function.

If I have an array of numbers:

var tempArray = [12,45,2,67,86];

how come Math.min() can't look at all the numbers in the array at
once? i.e. - If I put all of the numbers in the array like so:

Math.min(12,45,2,67,86)

I get the lowest number, but when I try this:

Math.min(tempArray)

I get an error of NaN.


Cheers.
 
P

Pete

Hi, just a quick question about the Math.min() function.

If I have an array of numbers:

var tempArray = [12,45,2,67,86];

how come Math.min() can't look at all the numbers in the array at
once? i.e. - If I put all of the numbers in the array like so:

Math.min(12,45,2,67,86)

I get the lowest number, but when I try this:

Math.min(tempArray)

I get an error of NaN.

Cheers.

Math.min only accepts 2 or more numbers. It won't accept an array.
 
D

Douglas Crockford

Yansky said:
If I have an array of numbers:

var tempArray = [12,45,2,67,86];

how come Math.min() can't look at all the numbers in the array at
once? i.e. - If I put all of the numbers in the array like so:

Math.min(12,45,2,67,86)

I get the lowest number, but when I try this:

Math.min(tempArray)

I get an error of NaN.

Math.min.apply(Math, tempArray)

http://javascript.crockford.com/
 
R

RobG

works fine if your array doesn't have any undefined items.

If you have a sparse array and you know that there are no null values
(i.e. all the gaps are undefined) then copy the array, do a numeric
sort and get the value at index 0:

function asNum(a, b) { return a-b; }

function getMin(a) {
var b = a.concat()
return b.sort(asNum)[0];
}

var a = [];
a[500] = 13;
a[1000] = 0;
a[250] = 10;

alert(getMin(a));
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,160
Messages
2,570,890
Members
47,423
Latest member
henerygril

Latest Threads

Top