简体   繁体   English

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

[英]Assign only if condition is true in ternary operator in JavaScript

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?这可能吗?

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 ).如果您不想更改max = (max < b) ? b : max则需要将max重新分配给max

An if-statement is 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 :顺便说一句,如果你想避免重复变量名(或表达式?),你可以使用maximum 函数

max = Math.max(max, b);

An expression with ternary operator must have both values, ie 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 max will not change.在这种情况下,如果条件为假, max值不会改变。

You can just set max to 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;

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

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

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

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

我认为更好的方法可能是

max = Math.max(max, b)

你可以这样做:

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

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

The ternary operator is used where we have a minimum of two possible outcomes.三元运算符用于我们至少有两个可能的结果。

let no = 10;
let max = 20;

max = no > max ? no : max

if you only want to use if, not else, then I recommend you to use if not the ternary operator.如果您只想使用 if 而不是 else,那么我建议您使用 if not 三元运算符。

let no = 10;
let max = 20;
    
if (no > max){
   max = no
}

if you want to use ternary operator, but don't want to use else part, then you may use this, but this won't be useful in every problem如果你想使用三元运算符,但又不想使用 else 部分,那么你可以使用这个,但这并不是对每个问题都有用

let no = 10;
let max = 20;

no > max ? max = no : 0

here we are assigning value to a max variable only when the condition is true, otherwise, we are not doing anything在这里,我们仅在条件为真时才为 max 变量赋值,否则,我们什么也不做

Performace Results绩效结果

As most of the answers pretty much tell you almost every possible method, here are some performance results for the four most common methods over 40 million iterations and an average of 10 runs each. 由于大多数答案几乎告诉您几乎所有可能的方法,这里是四种最常见方法的一些性能结果,超过 4000 万次迭代,每种方法平均运行 10 次。

Using Ternary使用三元
For a = b > a? b: a 对于a = b > a? b: a a = b > a? b: a the average time was 90.8ms for 40,000,000 iterations over 10 runs a = b > a? b: a 10 次运行中40,000,000次迭代的平均时间为90.8 毫秒
Whereas for (b > a) && (a = b) the average time was 88.7ms for 40,000,000 iterations over 10 runs 而对于(b > a) && (a = b) 10 次运行的40,000,000次迭代,平均时间为88.7 毫秒

Using Math.max使用 Math.max
for a = Math.max(a, b) the average time was 117.3ms for 40,000,000 iterations over 10 runs 对于a = Math.max(a, b)在 10 次运行中40,000,000次迭代的平均时间为117.3 毫秒

Using an if statement使用 if 语句
for if (b > a) a = b the average time was 88.9ms for 40,000,000 iterations over 10 runs 对于if (b > a) a = b 10 次运行中40,000,000次迭代的平均时间为88.9 毫秒

Hope this was interesting! 希望这很有趣!

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 它会解决的,我想您想避免使用冒号,不幸的是,它不会发生

There was no example of ES6, we can use in this way:没有ES6的例子,我们可以这样使用:

let list = [{id: "abc", name: "test1"}, {id: "xyz", name: "test2"}]
let selectedData = {};
      list.some((exp) => {
        return (
          exp.id == "xyz" &&
          ((selectedData = exp), true)
        );
      })
console.log(selectedData);

Added description after a negative vote: Just adding a description to explain my solution.投反对票后添加说明:只需添加说明来解释我的解决方案。 If you have an array of objects and you want if only one condition satisfies then we can use some .如果您有一组对象,并且希望只有一个条件满足,那么我们可以使用some It will set the selectedData when the id == "xyz" .id == "xyz"时,它将设置selectedData As asked in the question, this will assign value only if the condition is true otherwise selectedData will be empty.正如问题中所问,仅当条件为真时才会赋值,否则selectedData将为空。

Instead of the ternary operator , you could use Logical AND assignment (&&=) .您可以使用逻辑与赋值 (&&=)代替三元运算符

Basic examples基本示例

 let output = false; output &&= true; console.log(output)

Reassignment is not possible because output has been defined as false .无法重新分配,因为output已定义为false

 const b = 10; const max = 1; let sum = max < b; sum &&= 'new value'; console.log(sum);

Returns a string, because the variable sum has been defined as true .返回一个字符串,因为变量sum已定义为true

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM