admin管理员组

文章数量:1302871

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?

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?

Share Improve this question edited Jan 1, 2014 at 12:25 user1804599 asked Jan 1, 2014 at 12:13 meenameena 1991 gold badge4 silver badges12 bronze badges 2
  • 2 What is cnttimearr? – p.s.w.g Commented Jan 1, 2014 at 12:15
  • write definition of cnttimearr also – AmanS Commented Jan 1, 2014 at 12:27
Add a ment  | 

2 Answers 2

Reset to default 5

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

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);

本文标签: How to avoid NaN when using the Mathmax() function in JavaScriptStack Overflow