【问题标题】:Looking for a way to simplify an if statement with multiple ||寻找一种方法来简化带有多个 || 的 if 语句
【发布时间】:2011-07-12 12:48:06
【问题描述】:

我有这个 JQuery / Javascript 代码块来按搜索词过滤我的列表。它很长,看起来有点不专业。有没有办法可以简化它?

比如“.contains()”?

如果有人能指出我正确的方向,我将不胜感激。谢谢!

这是代码;问我是否需要更多:

 $.each(catalog.products,
      function(index, value) {

          if ((filterValue == '' || filterValue == null)
                  || value.name.toUpperCase().indexOf(filterValue.toUpperCase()) != -1
                  || value.brand.toUpperCase().indexOf(filterValue.toLocaleUpperCase()) != -1
                  || value.category.toUpperCase().indexOf(filterValue.toUpperCase()) != -1
                  || value.sport.toUpperCase().indexOf(filterValue.toUpperCase()) != -1)
          {
              items.push('<li id="' + index + '">' +
                      '<a data-identity="productId"  href="./details.page?productId=' + index + '" >' +
                      '<img class="ui-li-thumb" src="' + value.thumbnail + '"/>' +
                      '<p>' + value.brand + '</p>' +
                      '<h3>' + value.name + '</h3>' +
                      '<span class="ui-li-count">' + value.price + ' $</span></li>') +
              '</a>';
          }

      }
        );

【问题讨论】:

  • 如果这是您需要的逻辑,那么它是简化的。可读性也有一些要说的。
  • 我认为codereview.stackexchange.com 是合适的网站询问
  • 谢谢,不知道这个地方。

标签: javascript jquery mobile filter


【解决方案1】:

“简化”代码的直接方法是

  var filterUpper = !filterValue || filterValue.toUpperCase();
  var test = function(s) {return s.toUpperCase().indexOf(filterUpper) != -1};

  if (!filterValue || test(value.name) || test(value.brand) || test(value.category) || test(value.sport))   {
   ...

【讨论】:

  • 太棒了。非常感谢您的帮助。
【解决方案2】:

我建议您阅读以下重构模式:

这个想法是你试图在那个 if 语句上推断出一些东西,它不是一个'indexOf',它是一个业务规则,试着给那个规则一个名字,然后把代码放在一个表达意图的方法中。

只是我的 0.02

【讨论】:

    【解决方案3】:

    我要做的第一件事是注意以下代码sn-p:

    (filterValue == '' || filterValue == null)
    

    可以改成

    !filterValue
    

    这是因为 null 或空字符串变量在 javascript 中被视为“虚假”,即当被视为布尔值时,这些值将转换为 false。

    然后我会像 Alexander Gessler [1] 所做的那样,将重复的 filterValue.toUpperCase() 分解出来。

    [1]Looking for a way to simplify an if statement with multiple ||

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-15
      • 1970-01-01
      相关资源
      最近更新 更多