首页 > 解决方案 > 数学最小值和最大值返回 NaN

问题描述

我想从一个数字数组中记录最小和最大数字,这些数字在运行时会不断变化。我正在使用 ES5Math.minMath.max. 我什至克隆输入数组以避免并发更改。这是我的代码:

var runTimes = input.runTimes.slice(0); // clone input to avoid further changes
console.log("RUN TIMES", runTimes);
var min = Math.min(runTimes);
var max = Math.max(runTimes);
console.log("RUN TIMES MIN", min);
console.log("RUN TIMES MAX", max);

NaN即使所有项目都是数字, 我也会得到日志验证:在此处输入图像描述

标签: javascriptmath

解决方案


Math.min或者Math.max不要期望数组而是不同的数字。请试试这个:

var min = Math.min(...runTimes);
var max = Math.max(...runTimes);

推荐阅读