javascript - 如何防止 Math.max() 返回 NaN?

标签 javascript

<分区>

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

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

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

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

max(thenum);                                                                      

最佳答案

发生这种情况的原因是 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 原型(prototype)。这样你就可以更轻松、更干净地使用它(覆盖原型(prototype)是危险的,你应该避免它 - 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

关于javascript - 如何防止 Math.max() 返回 NaN?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29485832/

相关文章:

javascript - 点击事件未触发

javascript - 如果 Google 应用程序脚本中省略了 var/const,我的 getter 会执行什么?

javascript - 在 Ionic 中将 $ionicSlideBoxDelegate 用于两个或多个幻灯片框

javascript - 查找对象中重复属性值的计数

javascript - 发出多个并行 REST 调用并等待 Node.js 中的所有结果的推荐方法

javascript - 为什么这里忽略了原型(prototype)方法?

javascript - 使用多个复选框进行 Jquery 过滤

javascript - 如何从数据库查询中取出 JavaScript 对象以在脚本的其余部分中进行访问

javascript - Three.js 初学者卡在第一步 : "undefined is not a function"

javascript - 着色器 : Best practice to store them