简体   繁体   中英

simplify if-statement in Javascript

$scope.vergleich = function () {
    if ($scope.relrechtsform.indexOf(dataService.dic.alt.rechtsformKanlei || dataService.dic.neu.rechtsformKanlei ) !== -1) {
        return true
    } else {
        return false;                   }
    }
}

I am currently student and intelliJ tells me I have to simplify this if-statement but I have no idea how. Maybe somebody can help me.

The simplification is probably that, if condition is a boolean, :

if (condition) { 
  return true;
} 
else { 
  return false;
}

is equivalent to

return condition;

However there also seems to be a logical error in your test.

$scope.relrechtsform.indexOf(dataService.dic.alt.rechtsformKanlei ||
                        dataService.dic.neu.rechtsformKanlei ) !== -1

Does not mean the same thing as :

$scope.relrechtsform.indexOf(dataService.dic.alt.rechtsformKanlei) !== -1 || 
$scope.relrechtsform.indexOf(dataService.dic.neu.rechtsformKanlei) !== -1

Maybe you're looking for this:

 $scope.vergleich = function () {
  return $scope.relrechtsform.indexOf(dataService.dic.alt.rechtsformKanlei || dataService.dic.neu.rechtsformKanlei ) !== -1;
};

Tân's version is a correct answer to your question. However, with recent JavaScript you can simplify even more thanks to array.includes :

$scope.vergleich = () =>
    $scope.relrechtsform.includes(dataService.dic.alt.rechtsformKanlei || dataService.dic.neu.rechtsformKanlei)

You can just use your condition instead of using IF else statement -:

$scope.vergleich = function () {
    return ($scope.relrechtsform.indexOf(dataService.dic.alt.rechtsformKanlei ||
                        dataService.dic.neu.rechtsformKanlei ) !== -1);
};

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