This question already has answers here:
How do you check that a number is NaN in JavaScript?
                            
                                (31个答案)
                            
                    
                4年前关闭。
        

    

我正在使用以下代码来更新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()

if (isNaN(distance))
    distance = 0;


您还可以使用内联条件将其压缩为一行:

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

08-07 20:28