Shortening a Javascript if-else structure

前端 未结 7 826
情书的邮戳
情书的邮戳 2021-02-13 00:05

The code I have is:

 var level = function (d) {
    if (value(d) > median + stdev) {
        return 1;
    } else if (value(d) > median) {
        return 2         


        
7条回答
  •  醉梦人生
    2021-02-13 00:11

    You can calculate the difference between the value and the median, which makes the comparisons simpler:

    function level(d) {
      var n = value(d) - median;
      if (n > stdev) {
        return 1;
      } else if (n > 0) {
        return 2;
      } else if (n > -stdev) {
        return 3;
      } else {
        return 4;
      }
    };
    

    You can also write it using the conditional operator instead of if statements:

    function level(d) {
      var n = value(d) - median;
      return n > stdev ? 1 :
        n > 0 ? 2 :
        n > -stdev ? 3 :
        4;
      }
    };
    

    Whether this is nicer or not is a matter of taste, but it's shorter.

提交回复
热议问题