Assign only if condition is true in ternary operator in JavaScript

橙三吉。 提交于 2019-11-26 16:04:50

问题


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?


回答1:


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);



回答2:


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.




回答3:


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;



回答4:


I think ternary is more suitable try this

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



回答5:


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

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



回答6:


I think a better approach could be

max = Math.max(max, b)



回答7:


look:

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

it's going to work out, I think you wanna avoid using a colon, unfortunately, it won't happen




回答8:


You can do something like this:

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


来源:https://stackoverflow.com/questions/15009194/assign-only-if-condition-is-true-in-ternary-operator-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!