【问题标题】:Short-hand boolean logic in JavaScriptJavaScript 中的简写布尔逻辑
【发布时间】:2017-02-18 19:09:56
【问题描述】:

我是 JavaScript 和 AngularJS 的初学者。所以我遇到了亚当弗里曼书籍中的以下代码

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

我对上面的return 语句感到困惑,你们能重新编写上面的代码吗?用清晰的代码(没有速记)。

谢谢。

【问题讨论】:

    标签: javascript angularjs boolean-logic conditional-operator shorthand


    【解决方案1】:

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

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

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

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

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

    return true || true;
    

    最终会简化为

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

    同样,您可以认为这个表达式通过替换值来返回值并分别计算它们。

    更长的版本是:

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

    【讨论】:

    • 长版本中不需要else 块。
    • @BenM 是的。我知道。把它放在那里是为了让 OP 更清楚,因为他是初学者。
    【解决方案2】:

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

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

    基本上,return 将返回 true,如果 任一 指定条件是 true。否则,它将返回false

    【讨论】:

      猜你喜欢
      • 2011-08-17
      • 1970-01-01
      • 2021-02-02
      • 2016-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多