Javascript conditional switch statement

前端 未结 4 1990
醉酒成梦
醉酒成梦 2020-11-27 15:07

Is there a way to write a conditional switch statement in javascript?

I\'m guessing not, since the following is always going to default:

    var raw         


        
4条回答
  •  野性不改
    2020-11-27 15:42

    Don't try this at home, or take it too seriously, this is just for sugary fun...

    function conditionalSwitch(value, cond, callback /* cond, callback, cond, callback, ... */ ) {
      for (var i = 1; i < arguments.length; i += 2) {
        if (arguments[i](value)) {
          arguments[i + 1](value);
          return;
        }
      }
    }
    
    
    
    function test(val) {
      let width, height;
    
      conditionalSwitch(val,
      
        (val) => val > 10,
        () => [height, width] = [48,36],
    
        (val) => val > 5,
        () => [height, width] = [40, 30],
    
        // Default
        () => true,
        () => [height, width] = [16, 12]
      )
      console.log(width, height);
    }
    
    
    test(4.9);  // 12 16
    test(5.1);  // 30 40
    test(10.1); // 36 48

提交回复
热议问题