Assign only if condition is true in ternary operator in JavaScript

后端 未结 9 1949
小鲜肉
小鲜肉 2020-12-02 22:08

Is it possible to do something like this in JavaScript?

max = (max < b) ? b;

In other words, assign value only if the condition is true.

9条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-02 22:56

    Don't use the ternary operator then, it requires a third argument. You would need to reassign max to max if you don't want it to change (max = (max < b) ? b : max).

    An if-statement is much more clear:

    if (max < b) max = b;
    

    And if you need it to be an expression, you can (ab)use the short-circuit-evaluation of AND:

    (max < b) && (max = b)
    

    Btw, if you want to avoid repeating variable names (or expressions?), you could use the maximum function:

    max = Math.max(max, b);
    

提交回复
热议问题