如何使用三元运算符(?:)或空合并运算符(??)编写if-else条件? [英] How to use ternary operator(?:) or Null Coalescing operator(??) to write if-else condition?

查看:52
本文介绍了如何使用三元运算符(?:)或空合并运算符(??)编写if-else条件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

if(country1 != null)
{ 
    country1 = "Turkey";
}
else
{
country1 = "ABD";
}

推荐答案

三元运算符使用三个操作数:

Ternary operators use three operands:

后跟?的条件,后跟一个表达式,以评估条件是否为真实",后跟一个:,后跟一个表达式,用于评估条件是否为 falsey .

A condition followed by a ?, followed by an expression to evaluate if the condition is 'truthy', followed by a :, followed by an expression to evaluate if the condition is falsey.

因此,在您的情况下,您想做的是这样:

So in your case, what you'd want to do is this:

country1 = country1 != null ? 'Turkey' : 'ABD';

您似乎对 ?? 运算符感到困惑. ?? 被称为空合并运算符

You seem a little confused about ?? operator. ?? is called Null Coalescing operator

x = x ?? 'foo';

等同于

if( x == null )
    x = 'foo';
else
    x = *whatever the value previously was*;

因此,如果我们在检查前将 x 设置为 bar ,它将不会更改为 foo ,因为 bar 不等于 null .另外,请注意,这里的 else 语句是多余的.

so if we have x set to bar before the check, it won't change to foo because bar is not equal to null. Also, note that the else statement here is redundant.

所以 ?? 仅在变量先前为空的情况下才会将其设置为某个值.

so ?? will set the variable to some value only if it was previously null.

在您的代码中,您试图分配两个值 Turkey ABD 中的一个,如果先前的值为null,则不分配单个值.这样就会出现语法错误.

In your code, you are trying to assign one of the two values Turkey or ABD, and not a single value if the previous value was null. So you get a syntax error.

所以,总结一下.

if() {}
else {}

可以使用三元运算符缩短吗?:.

if(){}

可以使用 ?? 运算符来缩短

,因为此处的else语句将只是多余的.

can be shortened using the ?? operator, because the else statement here will simply be redundant.

因此,等效的代码将不使用 ?? 运算符.

Thus, the equivalent of your code won't use ?? operator.

这篇关于如何使用三元运算符(?:)或空合并运算符(??)编写if-else条件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆