【问题标题】:NaN replacement in node.js with an integer [duplicate]用整数替换 node.js 中的 NaN [重复]
【发布时间】:2016-03-03 17:33:48
【问题描述】:

我正在使用以下代码更新 node.js 中的数据库

var mBooking = rows[0];
var distance = mBooking.distanceTravelled;
var lastLng = mBooking.lastLng;
var lastLat = mBooking.lastLat;

if(lastLat == 0)
{
    lastLat = lat;
    lastLng = lng;
}

var currentPoint = new GeoPoint(lat, lng);
var oldPoint     = new GeoPoint(lastLat, lastLng);

distance = distance + (currentPoint.distanceTo(oldPoint, true) * 1000);
if(distance == null)
    distance = 0;

var query = "UPDATE bookings SET lastLat = " + lat + ", lastLng = " + lng + ", distanceTravelled = " + distance + " WHERE id = " + mBooking.id;
console.log(query);

这是我的控制台查询

UPDATE bookings SET lastLat = 25.0979065, lastLng = 55.1634082, distanceTravelled = NaN WHERE id = 43

如何检查距离是否为 NaN,然后​​我可以将其替换为 0。

现在如果我尝试更新它会给出数据库错误

【问题讨论】:

  • IsNaN 就是你要找的东西
  • 自动更正。我不应该在手机上发帖
  • @JaromandaX SOAddict :)
  • IsNaN 函数中有一个函数,您可以按照 cmets 中的说明使用它。但我建议您避免使用它,因为它确实验证了一些字符串(“1E656716”等),如果希望将 distance 验证为整数,则可能不可靠。
    所以我建议在你的申请。如下所示:- function isInteger(distance) { return typeof distance === "number" && isFinite(distance) && Math.floor(distance) === distance; }

标签: javascript node.js socket.io


【解决方案1】:

使用isNaN()

if (isNaN(distance))
    distance = 0;

您也可以使用 inline-if 将其压缩为一行:

distance = (isNaN(distance) ? 0 : distance);

【讨论】:

    猜你喜欢
    • 2015-03-02
    • 2018-11-13
    • 2021-06-27
    • 2021-11-20
    • 2018-06-28
    • 2012-09-24
    • 2017-08-25
    • 2013-10-30
    • 1970-01-01
    相关资源
    最近更新 更多