JavaScript 中的简写布尔逻辑

Short-hand boolean logic in JavaScript

我是 JavaScript 和 AngularJS 的初学者。所以我遇到了 Adam Freeman 书中的以下代码

var selectedCategory = null;
...
$scope.categoryFilterFn = function(product) {
   return selectedCategory == null || 
      product.category === selectedCategory;
};

我被上面的return语句弄糊涂了,你们能不能重写上面的代码,代码清晰(没有shorthand)。

谢谢。

return 语句可以很容易地重写为 if() 块,如下所示:

$scope.categoryFilterFn = function(product) {

   if( selectedCategory == null || product.category === selectedCategory )
   {
       return true;
   }

   return false;
};

本质上,如果指定条件中的任一truereturn将变为returntrue。否则会returnfalse.

这是 returning boolean 值的简写形式。仔细看:

 return selectedCategory == null || product.category === selectedCategory;

这里,return语句有两个表达式:

  1. selectedCategory == null
  2. product.category === selectedCategory

当方法returns时,它将分别计算这两个表达式。考虑你的 selectedCategorynull,而 product.category 等于 selectedCategory 那么语句是

return true || true;

最终会简化为

return true; // (true || true) = true

同样,你可以通过代入值来思考这个表达式return的值,然后分别求值。

更长的版本是:

if (selectedCategory == null || product.category == selectedCategory) {
  return true;
} else {
  return false;
}