三元運算符react
The ternary operator "?:" earns its name because it's the only operator to take three operands. It is a conditional operator that provides a shorter syntax for the if..then..else statement. The first operand is a boolean expression; if the expression is true then the value of the second operand is returned otherwise the value of the third operand is returned:
三元運算符“?:”之是以得名,是因為它是唯一接受三個操作數的運算符。 它是一個條件運算符 ,可為if..then..else語句提供較短的文法。 第一個操作數是布爾表達式; 如果表達式為true,則傳回第二個操作數的值,否則傳回第三個操作數的值:
boolean expression? value1 : value2
例子: ( Examples: )
The following if..then..else statement:
以下if..then..else語句:
boolean isHappy = true;
String mood = "";
if (isHappy == true)
{
mood = "I'm Happy!";
}
else
{
mood = "I'm Sad!";
}
can be reduced to one line using the ternary operator:
可以使用三元運算符減少到一行:
boolean isHappy = true;
String mood = (isHappy == true)?"I'm Happy!":"I'm Sad!";
Generally the code is easier to read when the if..then..else statement is written in full but sometimes the ternary operator can be a handy syntax shortcut.
通常,如果完全編寫if..then..else語句,則代碼更易于閱讀,但有時三元運算符可以是友善的文法快捷方式。
翻譯自: https://www.thoughtco.com/ternary-operator-2034302
三元運算符react