我有一个非常简单的 if 语句,但我没有过多地使用 javascript,所以我认为我在某处犯了错误。如果您转到我的页面,您会看到该值被警告为未定义,但即使 if 参数为 == undefined
,代码块仍会被跳过。这是 AngularJS 应用重要吗?
网页:http://alainwebdesign.ca/pl2/#/petType
JavaScript:
$scope.setDate = function (dateSelected) {
alert(dateSelected);
var now = new Date();
$scope.latest = new Date(now.getFullYear(), now.getMonth(), now.getDate(), now.getHours(), now.getMinutes());
$scope.hoursAgo = Math.round((($scope.latest - dateSelected) / 3600000) * 100) / 100;
if ($scope.hoursAgo === undefined || $scope.hoursAgo == NaN) {
alert("Please choose a date/time");
}
else {
alert('You lost your pet ' + $scope.hoursAgo + ' hour(s) ago');
$scope.checkDateSet = true;
}
}
最佳答案
您的问题不在于您的 if 语句。 Javascript 中的 NaN
有些特殊。
例如:
NaN === NaN//假
您可以在这里阅读更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN
将支票更改为:
if ($scope.hoursAgo === undefined || isNaN($scope.hoursAgo)) {
...
} else {..}
关于javascript - 将日期与 NaN 和 undefined 进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39976077/