【问题标题】:How to prevent Math.max() return NaN? [duplicate]如何防止 Math.max() 返回 NaN? [复制]
【发布时间】:2015-06-11 17:02:31
【问题描述】:

我想创建一个从数组中返回最大数的函数,但它一直返回NaN

如何防止 NaN 并返回想要的结果?

var thenum = [5,3,678,213];

function max(num){
    console.log(Math.max(num));
}

max(thenum);                                                                      

【问题讨论】:

    标签: javascript


    【解决方案1】:

    发生这种情况的原因是Math.max 会根据其参数计算最大值。并且看到第一个参数是一个返回 NaN 的数组。

    您现在有 2 个选项(取决于您的环境或偏好):

    ES6(带有扩展语法)

    您可以将数组传播到函数的参数。

    const thenum = [5, 3, 678, 213];
    
    console.log(Math.max(...thenum));
    

    更多关于the spread syntax

    here 是这个例子的 jsFiddle。


    ES5(无扩展语法)

    或者,您可以使用apply 方法调用它,该方法允许您调用函数并在数组中为它们发送参数。

    您想要的是应用Math.max 函数,如下所示:

    var thenum = [5, 3, 678, 213];
    
    function max(num){
        return Math.max.apply(null, num);
    }
    
    console.log(max(thenum));
    

    您也可以将其设为方法并将其附加到 Array 原型。通过这种方式,您可以更轻松、更清洁地使用它(覆盖原型很危险,您应该避免这样做 - Read more about it)。像这样:

    Array.prototype.max = function () {
        return Math.max.apply(null, this);
    };
    console.log([5, 3, 678, 213].max());
    

    更多关于the apply method

    here 是两者的 jsFiddle

    【讨论】:

    • 答案应该更新添加展开算子solutoin
    • @CristianTraìna 感谢您的提醒。编辑了帖子:)
    【解决方案2】:

    试试这个。 Math.max.apply(Math,thenum)

    var thenum = [5,3,678,213];
    
    function max(num){
        console.log(Math.max.apply(Math,thenum));
    }
    

    结果:678

    【讨论】:

      【解决方案3】:
      var p = [35,2,65,7,8,9,12,121,33,99];
      
      Array.prototype.max = function() {
        return Math.max.apply(null, this);
      };
      
      Array.prototype.min = function() {
        return Math.min.apply(null, this);
      };
      
      
      alert("Max value is: "+p.max()+"\nMin value is: "+ p.min());  
      

      demo

      【讨论】:

        【解决方案4】:

        Math.max() 方法不允许您传入数组。所以对于 Array 你必须使用 Function.prototype.apply(),例如

        Math.max.apply(null, Array);
        

        参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply

        【讨论】:

          猜你喜欢
          • 2018-10-24
          • 1970-01-01
          • 2023-02-23
          • 2015-12-15
          • 2017-08-23
          • 1970-01-01
          • 2017-11-16
          • 2020-09-10
          相关资源
          最近更新 更多