在node.js中用整数替换NaN

时间:2015-11-30 06:21:23

标签: javascript node.js socket.io

我使用以下代码更新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替换它。

目前如果我尝试更新它会导致数据库错误

1 个答案:

答案 0 :(得分:2)

使用isNaN()

if (isNaN(distance))
    distance = 0;

您还可以使用inline-if:

将其压缩到一行
distance = (isNaN(distance) ? 0 : distance);