仅当 JavaScript 中的三元运算符中的条件为真时才赋值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15009194/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 23:09:17  来源:igfitidea点击:

Assign only if condition is true in ternary operator in JavaScript

javascriptternary-operator

提问by codiac

Is it possible to do something like this in JavaScript?

有可能在 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?

换句话说,仅当条件为真时才赋值。如果条件为假,则什么都不做(不赋值)。这可能吗?

回答by Bergi

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

然后不要使用三元运算符,它需要第三个参数。如果您不想更改 ( ) maxmax则需要重新分配给max = (max < b) ? b : max

An if-statementis much more clear:

一个if语句更加清晰:

if (max < b) max = b;

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

如果你需要它是一个表达式,你可以(ab)使用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);

回答by marekful

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

带有三元运算符的表达式必须具有两个值,即对于 true 和 false 情况。

You can however

不过你可以

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

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

在这种情况下,如果条件为假,则值max不会改变。

回答by Rocket Hazmat

You can just set maxto itself if the condition is false.

max如果条件为假,您可以设置为自身。

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.

if(max < v) max = b;

回答by Aditya

I think ternary is more suitable try this

我认为三元更合适试试这个

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

回答by Charlie Kilian

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

没有不是三元运算符的特定运算符,但您可以像这样使用它:

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

回答by dpolicastro

I think a better approach could be

我认为更好的方法可能是

max = Math.max(max, b)

回答by Gaurav Singh

You can do something like this:

你可以这样做:

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

回答by Theristes Gomes

look:

看:

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

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

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

它会解决的,我想你想避免使用冒号,不幸的是,它不会发生