javascript - 为什么这个计算返回 -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
是一个整数
解决方案
为什么这个计算返回 -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)
返回一个空数组。
推荐阅读
- github - github操作失败?tar 空存档,docker run 失败,退出代码为 1
- batch-file - 在子命令提示符下批量运行命令
- javascript - AJAX 调用后单击更改变量
- mysql - Debezium - MySQL 从连接偏移量手动更改 binlog 位置
- c++ - 为什么数组不打印第一个元素?
- c++ - abort() 已在项目中调用
- javascript - 在 Javascript 中遍历对象值
- asynchronous - 如何使用 Stream 和 Completer 在 dart 中下载文件
- salesforce - 在新选项卡/窗口中打开 VF 页面
- mongodb - MongoDB Compass 无法连接到服务器,但命令行有效