Assign only if condition is true in ternary operat

2019-01-11 09:52发布

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. If the condition is false, do nothing (no assignment). Is this possible?

6条回答
forever°为你锁心
2楼-- · 2019-01-11 10:25

I think a better approach could be

max = Math.max(max, b)
查看更多
时光不老,我们不散
3楼-- · 2019-01-11 10:30

An expression with ternary operator must have both values, i.e. for both the true and false cases.

You can however

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

in this case, if condition is false, value of max will not change.

查看更多
干净又极端
4楼-- · 2019-01-11 10:30

I think ternary is more suitable try this

(max < b) ? max = b : '';
查看更多
爱情/是我丢掉的垃圾
5楼-- · 2019-01-11 10:39

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;
查看更多
叼着烟拽天下
6楼-- · 2019-01-11 10:43

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);
查看更多
Bombasti
7楼-- · 2019-01-11 10:48

There isn't a specific operator that isn't the ternary operator, but you can use it like this:

max = (max < b) ? b : max;
查看更多
登录 后发表回答