What is the best way to replace or substitute if..else if..else trees in programs?

后端 未结 21 1200
迷失自我
迷失自我 2020-11-28 06:23

This question is motivated by something I\'ve lately started to see a bit too often, the if..else if..else structure. While it\'s simple and has its uses, somet

21条回答
  •  情书的邮戳
    2020-11-28 07:03

    Use a Ternary Operator!

    Ternary Operator(53Characters):

    i===1?doOne():i===2?doTwo():i===3?doThree():doNone();
    

    If(108Characters):

    if (i === 1) {
    doOne();
    } else if (i === 2) {
    doTwo();
    } else if (i === 3) {
    doThree();
    } else {
    doNone();
    }
    

    Switch((EVEN LONGER THAN IF!?!?)114Characters):

    switch (i) {
    case 1: doOne(); break;
    case 2: doTwo(); break;
    case 3: doThree(); break;
    default: doNone(); break;
    }
    

    this is all you need! it is only one line and it is pretty neat, way shorter than switch and if!

提交回复
热议问题