NaN replacement in node.js with an integer [duplic

2019-09-09 21:03发布

问题:

This question already has an answer here:

  • How do you check that a number is NaN in JavaScript? 30 answers

I am using following code to update database in 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);

This is my console query

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

How can i put a check to see if distance is NaN then i can replace it with 0.

For now if i try to update it gives database error

回答1:

Use isNaN().

if (isNaN(distance))
    distance = 0;

You can also condense this to one line with an inline-if:

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