Why does Math.min([1,2]) return NaN?

后端 未结 3 468
野性不改
野性不改 2020-12-30 17:37

I\'ve been debugging this code for about an hour, and it looks like Math.min([1,2]) returns NaN.

var int_array = [1,2]
console.log(         


        
相关标签:
3条回答
  • 2020-12-30 18:04

    This

    var int_array = [1,2];
    console.log(Math.min.apply(null,int_array));
    

    will work in all actual browsers.

    0 讨论(0)
  • 2020-12-30 18:13

    You pass an array as first parameter to min function

    Math.min([1,2])
    

    From MDN

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

    0 讨论(0)
  • 2020-12-30 18:22

    The Math.min() function actually expects a series of numbers, but it doesn't know how to handle an actual array, so it is blowing up.

    You can resolve this by using the spread operator ...:

    var int_array = [1,2];
    console.log(Math.min(...int_array)); // returns 1
    

    You could also accomplish this via the Function.apply() function that would essentially do the same thing but isn't as pretty :

    var int_array = [1,2];
    console.log(Math.min.apply(null,int_array)); // returns 1
    
    0 讨论(0)
提交回复
热议问题