首页 > 解决方案 > 为什么这个计算返回 -Infinity?

问题描述

所以我需要在我的脚本中做一些简单的减法计算,但事实证明它并不那么简单,我在这里做错了什么?

x= dbo.collection("master").find({Process: "Process1"}).toArray(); //Query my Mongo database
s1 = Math.max.apply(null, x.map(o => o.NumberInt)); //narrow down query to find the correct number 
s2 = (s1-1); //minus 1 from the result to find next result
//s2 returns -Infinity

我 100% 确定这s1是一个整数

标签: javascriptnode.js

解决方案


为什么这个计算返回 -Infinity?

Math.max.apply(null, input)检查可以返回的条件很容易Infinity-Infinity

function  doTheMagic(input){
    return Math.max.apply(null, input);
}


console.log(doTheMagic([1,2]));
console.log(doTheMagic(["1","2"]));
console.log(doTheMagic([null, undefined]));
console.log(doTheMagic([Infinity]));
console.log(doTheMagic(null));
console.log(doTheMagic({}));
console.log(doTheMagic([]));

-Infinity出现在您有 null、空数组或空白对象的任何地方 - 可能还有其他一些。这些是您的代码最有可能的结果。

我会四处走动,并建议您x.map(o => o.NumberInt)返回一个空数组。


推荐阅读