Shortening a Javascript if-else structure

前端 未结 7 828
情书的邮戳
情书的邮戳 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条回答
  •  -上瘾入骨i
    2021-02-13 00:23

    "nicer" way? No, not really.

    Alternate way(s) - yes, plentiful.

    One possibility is storing the condition and result in an array

    var levelFunctions = [
      { func: function(d){ return value(d) > median + stdev; }, val:1},
      { func: function(d){ return value(d) > median ; }, val:2},
      { func: function(d){ return value(d) > median - stdev; }, val:3},
      { func: function(d){ return true; }, val:4}
    ];
    

    Then just enumerating that list as part of the function

    var level = function (d) {
        for(var i=0;i

    A bit easy to extend than your original, but by [diety] its ugly as sin!

提交回复
热议问题