“elseif” syntax in JavaScript

后端 未结 8 822
刺人心
刺人心 2020-11-29 17:59

How can I achieve an elseif in a JavaScript condition?

相关标签:
8条回答
  • 2020-11-29 18:18

    Conditional statements are used to perform different actions based on different conditions.

    Use if to specify a block of code to be executed, if a specified condition is true

    Use else to specify a block of code to be executed, if the same condition is false

    Use else if to specify a new condition to test, if the first condition is false

    0 讨论(0)
  • 2020-11-29 18:20

    You could use this syntax which is functionally equivalent:

    switch (true) {
      case condition1:
         //e.g. if (condition1 === true)
         break;
      case condition2:
         //e.g. elseif (condition2 === true)
         break;
      default:
         //e.g. else
    }
    

    This works because each condition is fully evaluated before comparison with the switch value, so the first one that evaluates to true will match and its branch will execute. Subsequent branches will not execute, provided you remember to use break.

    Note that strict comparison is used, so a branch whose condition is merely "truthy" will not be executed. You can cast a truthy value to true with double negation: !!condition.

    0 讨论(0)
  • 2020-11-29 18:21

    You are missing a space between else and if

    It should be else if instead of elseif

    if(condition)
    {
    
    } 
    else if(condition)
    {
    
    }
    else
    {
    
    }
    
    0 讨论(0)
  • 2020-11-29 18:28

    Just add a space:

    if (...) {
    
    } else if (...) {
    
    } else {
    
    }
    
    0 讨论(0)
  • 2020-11-29 18:32

    Actually, technically when indented properly, it would be:

    if (condition) {
        ...
    } else {
        if (condition) {
            ...
        } else {
            ...
        }
    }
    

    There is no else if, strictly speaking.

    (Update: Of course, as pointed out, the above is not considered good style.)

    0 讨论(0)
  • 2020-11-29 18:36
    x = 10;
    if(x > 100 ) console.log('over 100')
    else if (x > 90 ) console.log('over 90')
    else if (x > 50 ) console.log('over 50')
    else if (x > 9 ) console.log('over 9')
    else console.log('lower 9') 
    
    0 讨论(0)
提交回复
热议问题