简体   繁体   中英

JavaScript true false not executing correctly in if else statement

For some reason when I'm using the true/false values and checking if at least one of the values is true, the if/else statement is not working correctly. I have this:

 $scope.checkValues = function (qId) {
   var airport = $scope.airports[0].questID;
   var destAirport = $scope.destAirports[0].questID;
   var airportVal = isFalseOrUndefined($scope.answers[airport]);
   var destAirportVal = isFalseOrUndefined($scope.answers[destAirport])
   if (airportVal == false || destAirportVal == false) {
     $surveyNav.skipPage = true;
   }
 }

 function isFalseOrUndefined(val) {
   if(val == null || val === false) {
     return true;
   } else {
     return false;
   }
 }

In this image below, as you can see the value for airportVal is true, the other value for destAirportVal in that same scenario is true, but I'm still able to get correctly in to the if condition and set the scope value.

在此处输入图片说明

Does anyone see any issue?

You should be using === and !== operators when checking for equality in Javascript. Javascript Comparison and Logical operators

op1 === op2 - Will check if op1 is explicitly equal to op2

op1 !== op2 - Will check if op1 is not explicitly equal to op2

Also: you can condense you isFalseOrUndefined function

Note 1: you are not actually checking if val is undefined. To check if something is undefined: typeof val === 'undefined' This is different than checking if a variable is null

Note 2: Keep in mind that your variables are not entirely clear here. airportVal will be equal to true when $scope.answers[airport] is false or null. Is this your intention?

$scope.checkValues = function (qId) {
    var airport = $scope.airports[0].questID;
    var destAirport = $scope.destAirports[0].questID;
    var airportVal = isFalseOrUndefined($scope.answers[airport]);
    var destAirportVal = isFalseOrUndefined($scope.answers[destAirport])

    if (airportVal === false || destAirportVal === false) {
        $surveyNav.skipPage = true;
    }
}

function isFalseOrUndefined(val) {
    return (val === null || val === false);
}

Your function should probably do what it claims to do:

function isFalseOrUndefined(val) {
   return typeof val === 'undefined' || val === false || val === null || val === ''/* add this if you think it should be falsy*/;
}

But then, testing for !val should be sufficient:

$scope.checkValues = function (qId) {
    var airport = $scope.airports[0].questID;
    var destAirport = $scope.destAirports[0].questID;
    if (!airport || !destAirport) {
          $surveyNav.skipPage = true;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM