JavaScript中的短手布尔逻辑

[英]Short-hand boolean logic in JavaScript


I'm beginner on JavaScript and AngularJS. So I encounter following code from Adam Freeman books

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

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

I get confused by the return statement above, can you guys re-write the code above with clear code (no shorthand).

我对上面的return语句感到困惑,你们可以用清晰的代码重写上面的代码(没有简写)。

Thanks.

谢谢。

2 个解决方案

#1


3  

This is a short-hand form of returning a boolean value. Look closely:

这是返回布尔值的简写形式。仔细看:

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

Here, return statement has two expressions:

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

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

When the method returns, it will evaluate these two expressions separately. Consider yout selectedCategory is null, and the product.category is equal to selectedCategory then the statement is

当方法返回时,它将分别评估这两个表达式。考虑yout selectedCategory为null,product.category等于selectedCategory然后语句为

return true || true;

which will eventually simplifies to

这将最终简化为

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

Likewise, you can think of this expressions return value by substituting values and evaluate them separately.

同样,您可以通过替换值并分别评估它来考虑此表达式返回值。

Longer version for this is:

更长的版本是:

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

#2


2  

The return statement could be re-written easily as an if() block as follows:

return语句可以作为if()块轻松重写,如下所示:

$scope.categoryFilterFn = function(product) {

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

   return false;
};

Essentially, the return is going to return true if either of the specified conditions is true. Otherwise, it will return false.

实质上,如果任一指​​定条件为真,则返回将返回true。否则,它将返回false。

智能推荐

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.itdaan.com/blog/2016/10/10/86e88089362871d9df1adfd51cb4d3d7.html



 
© 2014-2019 ITdaan.com 粤ICP备14056181号  

赞助商广告