【问题标题】:What is the best way to fix this triple-nested ternary operator?修复这个三重嵌套三元运算符的最佳方法是什么?
【发布时间】:2021-10-03 18:24:12
【问题描述】:

我有一个对对象数组进行排序的代码 sn-p。每个对象看起来都像:

{
      "id": "60ff9eb7c793c6197dae5d42",
      "matches": 1,
      "timestamp": "2021-07-27T05:46:52.469Z",
      "likes": 23
}

我有一个三重嵌套的三元表达式,它首先按匹配排序,然后按喜欢排序,然后按时间戳排序。代码如下。

        bestMatches.sort((a, b) =>
          a.matches < b.matches
            ? 1
            : a.matches === b.matches
            ? a.likes < b.likes
              ? 1
              : a.likes === b.likes
              ? a.timestamp.getTime() < b.timestamp.getTime()
                ? 1
                : -1
              : -1
            : -1
        );

将其转换为“好”代码的最佳方法是什么?在这种情况下,我在使用 if/else 时遇到了很多困难,而且我知道嵌套三元表达式是不好的做法。与往常一样,如果您花时间回答或尝试回答这个问题,感谢您抽出宝贵时间。

【问题讨论】:

    标签: javascript nested conditional-operator


    【解决方案1】:

    减去得到matches,然后是likes,然后是时间之间的差。

    bestMatches.sort((a, b) => (
      (b.matches - a.matches) ||
      (b.likes - a.likes) ||
      (b.timestamp.getTime() - a.timestamp.getTime())
    ));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-10-13
      • 2012-02-02
      • 2020-11-05
      • 2015-12-09
      • 2011-10-29
      • 2020-04-12
      相关资源
      最近更新 更多