Assign only if condition is true in ternary operator in JavaScript

后端 未结 9 1920
小鲜肉
小鲜肉 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 22:49

    you can try:

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

    look at this example:

    let max = 10;
    let b = 15;
    (max < b) && (max = b)// this will be true
    console.log("max=", max);
    
    let maxx = 10
    let bb = 5;
    (maxx < bb) && (maxx = bb)// this will be false
    console.log("maxx=", maxx);

提交回复
热议问题