shortHand if else-if and else statement

后端 未结 2 373
迷失自我
迷失自我 2020-12-16 03:03

I have nested if else statements, which I added below in two statements, Instead of having a lot of lines I am looking to shorthand it.

Can anyone help me out.

相关标签:
2条回答
  • 2020-12-16 03:27

    The short hand version is know as Ternary logic. It is pretty simple but if you have conditions that need a lot of updating, it might get confusing. But here it is:

    Statement 1:
    
    var a = -1;
    var b = -1;
    var c = -1;
    var d = -1;
    
    result = ((a && b) !== -1) ? 'hai' :
         ((c && d) !== -1) ? 'hello' : 'hurray';
    
    alert(result);
    

    Statement 2:
    
    var a = 'abc';
    var bb = 'def';
    
    // plug in the remaining variables to test further 
    
    result = (a === 'abc') ? (bb === 'def') ? amd = 'hello' :
             (bb === 'ghi') ? amd = 'hai' : amd = 'Hurray' :
         (a === 'que') ? (aaa === 'ffffd') ? amd = 'Hurray Hi' : amd = 'Hurray Bye' : 
         'default result was missing from your statment';
    
    alert(result);
    

    That should do it. Although it is 'shorthand', it can be more confusing in the long run.

    0 讨论(0)
  • 2020-12-16 03:42

    Statement : 1 can be written as,

    abc = (a !== -1 && b!== -1) ? "hai" : (c !== -1 && d!== -1) ? "hello" : "hurray";
    

    So based on this try to write your own code for the statement 2 [Hint : use switch for that]

    0 讨论(0)
提交回复
热议问题