将日期与NaN和未定义进行比较

Comparing date to NaN and undefined

本文关键字:比较 未定义 日期 NaN      更新时间:2023-09-26

我有一个非常简单的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 // false

您可以在这里阅读更多内容:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN

将支票更改为:

if ($scope.hoursAgo === undefined || isNaN($scope.hoursAgo)) {
...
} else {..}

检查if ($scope.hoursAgo === undefined || $scope.hoursAgo == NaN)

像这样写

if ($scope.hoursAgo === 'undefined' || isNaN($scope.hoursAgo)) {