meena
meena

Reputation: 199

How to avoid NaN when using the Math.max() function in JavaScript?

I am trying the get the maximum value in an array of numbers:

maxtime=Math.max.apply( Math, cnttimearr );
alert(maxtime);

However, I am getting NaN instead of the maximum value. Can anyone tell me what I am doing wrong?

Upvotes: 9

Views: 6906

Answers (2)

AmanS
AmanS

Reputation: 1510

Check out your array cnttimearr that all the values should be convertible to numbers

cnttimearr= [5, 6, 2, 3, 7];    /*your array should be like this */

maxtime = Math.max.apply(Math, cnttimearr); 
/* This about equal to Math.max(cnttimearr[0], ...) or Math.max(5, 6, ..) */
alert(maxtime);

Upvotes: 1

user1804599
user1804599

Reputation:

Read the manual.

If at least one of arguments cannot be converted to a number, the result is NaN.

Make sure all the elements in the array are convertible to numbers.

> xs = [1, 2, '3'];
[1, 2, "3"]
> Math.max.apply(Math, xs);
3
> xs = [1, 2, 'hello'];
[1, 2, "hello"]
> Math.max.apply(Math, xs);
NaN

Upvotes: 5

Related Questions