Assign only if condition is true in ternary operator in JavaScript

后端 未结 9 1944
小鲜肉
小鲜肉 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条回答
  •  半阙折子戏
    2020-12-02 23:00

    You can just set max to itself if the condition is false.

    max = (max < b) ? b : max;
    

    Or you can try using the && operator:

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

    Or to keep your code simple, just use an if.

    if(max < v) max = b;
    

提交回复
热议问题