NaN replacement in node.js with an integer [duplicate]

安稳与你 提交于 2020-01-07 03:08:20

问题


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);


来源:https://stackoverflow.com/questions/33992553/nan-replacement-in-node-js-with-an-integer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!