abc类路由
If you made it this far then it's either you know of ternary operators and want to know more, you have no idea of ternary operators, or you’re just somewhere in-between. Keep on.
如果到此为止,那么要么是您了解三元运算符,然后想了解更多,要么您不知道三元运算符,或者您只是介于两者之间。 继续。
From my time writing JavaScript, and of course looking through the JavaScript of others especially beginner developers, I have noticed the age-long trend of using if/else
statements and really long chains of them too! As an advocate of DRY code -Don’t Repeat Yourself, I ensure my code stays DRY, and maybe cold-hearted, lol.
从我写JavaScript的时间开始,当然还有在其他人(尤其是初学者)JavaScript浏览中,我注意到使用if/else
语句的历史已久,而且它们的链条也很长! 作为DRY代码的倡导者-不要重复自己,我确保我的代码保持DRY,或者冷漠,大声笑。
In this post, we’ll be explaining ternary operators in the simplest way and how they make coding and life in general, easier.
在本文中,我们将以最简单的方式说明三元运算符,以及它们如何使编码和一般生活变得更轻松。
JavaScript中的运算符 ( Operators in JavaScript )
In the JavaScript theatre, various operations require operators, which are basically denoted with symbols- + - / = * %
. For the various operations like arithmetic and assignment operations, various symbols are used. These operators in their usage are split into 3 types:
在JavaScript剧院中,各种操作都需要运算符,这些运算符基本上用符号+ - / = * %
。 对于算术运算和赋值运算之类的各种运算,将使用各种符号。 这些运算符的用法分为3种类型:
- Unary Operators - Requires one operand either before or after the operator. 一元运算符 -在运算符之前或之后需要一个操作数。
- Binary Operators - Requires two operands on either side of the operator. 二进制运算符 -在运算符的任一侧都需要两个操作数。
- Ternary Operator - Requires three operands and is a conditional operator. 三元运算符 -需要三个操作数,是一个条件运算符。
time++ //Unary operator (increment)
2 + 3 //Binary Operator (addition)
a ? 'hello' : 'world' //Ternary/Conditional operator
We will focus on the ternary operator as earlier stated.
如前所述,我们将重点介绍三元运算符。
三元运算符 ( Ternary Operator )
The ternary operator has been around for a while now, but isn’t widely used, maybe because of the syntax or some form of ambiguity I’m unaware of. The ternary operator is a conditional operator and can effectively and efficiently replace several lines of IF statements. It simply verifies if a condition is true or false and returns an expression or carry out an operation based on the state of the condition, in probably one line of code. Using an IF statement we have:
三元运算符已经存在了一段时间,但并未广泛使用,可能是因为我不知道的语法或某种形式的歧义。 三元运算符是条件运算符,可以有效地替换几行IF语句。 它仅用一条代码来验证条件是真还是假,然后根据条件的状态返回表达式或执行操作。 使用IF语句,我们可以:
var day = true;
if(day){
alert('It is day-time')
} else{
alert('It is night-time')
}
// It is day-time
Using the ternary operator:
使用三元运算符:
var day = true; //conditon
alert(day ? 'It is day-time' : 'It is night-time') // It is day-time
This reduced the syntax of the IF statement to:
这将IF语句的语法简化为:
- ? - means IF
- : - means Else
So, if day
is true
, alert It is daylight
, else alert It is nighttime
. Simple!
因此,如果day
为true
,则警报It is daylight
,否则警报It is nighttime
。 简单!
Let’s get to more details.
让我们来了解更多细节。
变量分配 ( Variable Assignment )
As stated earlier, the result of the condition evaluation can be an expression or an operation, and in this case a variable assignment.
如前所述,条件评估的结果可以是表达式或运算,在这种情况下可以是变量赋值。
var myName = false;
var age = false;
var message = myName ? "I have a name" : "I don't have a name, duh!"
console.log(message) // I have don't have a name, duh!
myName = true;
message = myName ? age = true : 'Get out of here, nameless'
console.log(message) // true
Notice we assigned the result of a ternary operation first to a global variable message
, and later on, reassigned it when the condition changed. Notice the reassignment of the global variable age
in the condition of the ternary operator. Reassignment operations can occur in a ternary operation - so much done in one line yeah? The ELSE
part of the operation can also be an expression or an operation on its own, just like it’s done in conventional IF
statements.
请注意,我们首先将三元运算的结果分配给全局变量message
,然后在条件改变时重新分配它。 注意在三元运算符条件下全局变量age
的重新分配。 重新分配操作可以在三元操作中进行-在一行中完成了太多工作了吗? 该操作的ELSE
部分也可以是表达式或单独的操作,就像在常规IF
语句中所做的一样。
功能用法 ( Usage in Functions )
Usually, the next use case for IF statements are in functions, basically ternary operations make a function ‘syntactically sweet’. Same way variables are assigned the result of ternary operations is the same way functions return the result of ternary operations. With IF statements we have:
通常,IF语句的下一个用例在函数中,基本上三元运算使函数“在语法上很甜蜜”。 给变量分配三元运算结果的方式与向函数返回三元运算结果的方式相同。 使用IF语句,我们可以:
var dog = true;
function myPet(){
if(dog){
return 'How do i get it?';
} else {
return 'Get me a dog!';
}
}
console.log(myPet()) // How do i get it?
with a ternary operator:
使用三元运算符:
var dog = false;
function myPet(){
return dog ? 'How do i get it?' : 'Get me a dog!';
}
console.log(myPet()) // Get me a dog!
Imagine if we had quite a number of IF statements, with a host of return
expressions in them, now think of how these can be shortened using ternary operators. Next, we will see how we can chain multiple conditions together, you can have the conditions in functions as well!
想象一下,如果我们有很多IF语句,其中包含许多return
表达式,现在考虑如何使用三元运算符来缩短它们。 接下来,我们将看到如何将多个条件链接在一起,您也可以在函数中拥有条件!
多种条件 ( Multiple Conditions )
Just like in good old IF statement with IF/ELSE IF
, multiple conditions can be chained in ternary operations to give one robust operation. Normally we would write:
就像在具有IF/ELSE IF
旧IF语句中一样,可以在三元运算中链接多个条件以给出一个可靠的运算。 通常我们会这样写:
var myName = true;
var myAge = true;
var message = '';
if (myName){
if(myAge){
message = "I'll like to know your age and name"
}else{
message = "I'll stick with just your name then"
}
} else {
"Oh, I'll call you JavaScript then, cus you fine and mysterious"
}
console.log(message) //I'll like to know your age and name
but with a ternary operator we have:
但是使用三元运算符,我们可以:
var myName = true;
var myAge = true;
var message = myName? (myAge ? "I'll like to know your age and name" : "I'll stick with just your name") : "Oh, I'll call you JavaScript then, cus you fine and mysterious"
console.log(message) // I'll like to know your age and name
This is just a simple illustration of having two conditions in one IF statement. Here’s a lighter one:
这只是在一个IF语句中具有两个条件的简单说明。 这是一个较轻的:
var email = false;
var phoneNumber = true;
var message = email ? 'Thanks for reaching out to us' : phoneNumber ? 'Thanks for reaching out to us' : 'Please fill in your email or phone-number'
console.log(message) //Thanks for reaching out to us
Here we simply have multiple conditions chained to one another, and if a condition doesn’t pass, another condition is put forward, and if it still doesn’t pass, (now you cannot be offered any further assistance, lol) an expression is returned.
在这里,我们只是简单地将多个条件链接在一起,如果一个条件没有通过,则会提出另一个条件,如果仍然不通过,(现在您将无法获得任何进一步的帮助,大声笑),表达式是回来。
每个条件多次操作 ( Multiple Operations per Condition )
A friend of mine would say “in code, you read A + B but later you are required to pull B from a remote server, make A a ninja, minify B, before they can be added together”. So far we have seen multiple conditions chained together, what about expressions or conditions per condition? Say we would like to make a request to an API if a condition passes as true. Just like in IF statements, here’s a simple one:
我的一个朋友会说:“在代码中,您读了A + B,但后来您需要从远程服务器中拉出B,让A成为忍者,缩小B,然后再将它们加在一起”。 到目前为止,我们已经看到多个条件链接在一起,每个条件的表达式或条件如何? 假设条件满足,我们希望向API发出请求。 就像在IF语句中一样,这是一个简单的语句:
var home = true;
if(home){
alert('Welcome 127.0.0.1');
var port = prompt('What port do you like?');
alert('Serving you a cool dish on ' + port)
} else {
alert('Check back when you get home' )
}
//serving you a cool dish on ???
but with a ternary operator, simply separate each operation with a comma.
但使用三元运算符,只需用逗号分隔每个操作即可。
var home = true;
var port = '';
home ? (
alert('Welcome 127.0.0.1'),
port = prompt('What port do you like?'),
alert('Serving you a cool dish on ' + port)
) : alert('Check back when you get home' )
//serving you a cool dish on ???
Syntactic sugar!
语法糖!
Note: All variables used in a ternary operation should be defined before the operation is created. Also, If the operations in the condition are assignment operations, the value of the last expression or operation is used i.e
注意:三元运算中使用的所有变量都应在创建运算之前进行定义。 另外,如果条件中的操作是赋值操作,则使用最后一个表达式或操作的值,即
var home = true;
var myLocation = 'Lagos';
myLocation = home ? ('Brussels', 'london', 'Rio de Janero', 'Newark' ) : 'Kinshasha'
console.log(myLocation) // Newark
结论 ( Conclusion )
So far, you have seen how invaluable using ternary operators to write conditional statements make code plain and effortless, from writing simple lines of conditional statements to writing large chunks of chained operations in or out of functions. Using ternary operators, keep writing better code, …and DRY code.
到目前为止,您已经看到使用三元运算符编写条件语句使代码变得简单明了,从编写简单的条件语句行到在函数中或函数外编写大块链接操作。 使用三元运算符,继续编写更好的代码,以及DRY代码。
翻译自: https://scotch.io/tutorials/understand-the-javascript-ternary-operator-like-abc
abc类路由