Question mark and colon in JavaScript

前端 未结 7 1521
孤独总比滥情好
孤独总比滥情好 2020-11-21 11:36

I came across the following line

hsb.s = max != 0 ? 255 * delta / max : 0;

What do the ? and : mean in this conte

相关标签:
7条回答
  • 2020-11-21 11:58

    ? : isn't this the ternary operator?

    var x= expression ? true:false

    0 讨论(0)
  • 2020-11-21 12:04

    Be careful with this. A -1 evaluates to true although -1 != true and -1 != false. Trust me, I've seen it happen.

    so

    -1 ? "true side" : "false side"

    evaluates to "true side"

    0 讨论(0)
  • 2020-11-21 12:06

    It is called the Conditional Operator (which is a ternary operator).

    It has the form of: condition ? value-if-true : value-if-false
    Think of the ? as "then" and : as "else".

    Your code is equivalent to

    if (max != 0)
      hsb.s = 255 * delta / max;
    else
      hsb.s = 0;
    
    0 讨论(0)
  • 2020-11-21 12:07

    ?: is a short-hand condition for else {} and if(){} problems. So your code is interchangeable to this:

    if(max != 0){
           hsb.s = 225 * delta / max
    }
    else {
           hsb.s = 0
    }
    

    MDN - Conditional (Ternary) Operator

    0 讨论(0)
  • 2020-11-21 12:11

    Properly parenthesized for clarity, it is

    hsb.s = (max != 0) ? (255 * delta / max) : 0;
    

    meaning return either

    • 255*delta/max if max != 0
    • 0 if max == 0
    0 讨论(0)
  • 2020-11-21 12:14

    This is probably a bit clearer when written with brackets as follows:

    hsb.s = (max != 0) ? (255 * delta / max) : 0;
    

    What it does is evaluate the part in the first brackets. If the result is true then the part after the ? and before the : is returned. If it is false, then what follows the : is returned.

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