shortHand if else-if and else statement

后端 未结 2 372
迷失自我
迷失自我 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.

提交回复
热议问题