Why is math.max() returning NaN on an array of integers?

后端 未结 4 1878
太阳男子
太阳男子 2020-11-28 13:05

I am trying to get the highest number from a simple array:

data = [4, 2, 6, 1, 3, 7, 5, 3];

alert(Math.max(data));

I have read that if eve

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-28 13:54

    if you see doc for Math.max you can see next description

    Because max() is a static method of Math, you always use it as Math.max(), rather than as a method of a Math object you created (Math is not a constructor).

    If no arguments are given, the result is -Infinity.

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

    When you call Math.max with array parameter like

    Math.max([1,2,3])
    

    you call this function with one parameter - [1,2,3] and javascript try convert it to number and get ("1,2,3" -> NaN) fail.
    So result as expected - NaN

    NOTE: if array with just one number - all work correctly

     Math.max([23]) // return 23
    

    because [23] -> "23" -> 23 and covert to Number is done.


    If you want get max element from array you should use apply function, like

    Math.max.apply(Math,[1,2,3])
    

    or you can use the new spread operator

    Math.max(...[1,2,3])
    

提交回复
热议问题