欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JavaScript三元运算符

程序员文章站 2022-05-18 17:08:11
...

Ternary operators allow us to really quickly write shorter **if** statements

三元运算符允许我们真正快速地编写较短的** if **语句

Here's a quick example:

这是一个简单的例子:

// chris is level 100 cool
// everyone else is level 999
const howCoolAmI = name === 'chris' ? 100 : 999;

JavaScript三元运算符

Let's take a deeper look at how we can rewrite a simple if statement with and without a ternary operator:

让我们更深入地研究如何使用和不使用三元运算符来重写简单的if语句:

没有三元运算符 (Without a ternary operator)

// if statement without a ternary operator
let skillLevel;

if (name === 'chris') {
  skillLevel = 5;
} else {
  skillLevel = 10;
}

与三元运算符 (With a ternary operator)

We can rewrite the above with a ternary operator like so:

我们可以像这样用三元运算符重写上面的代码:

let skillLevel = name === 'chris' ? 5 : 10;
  • To use a ternary we will put the if statement on the left of the **?**.

    要使用三进制,我们将if语句放在**的左侧 ? **。
  • The first part after the ? will be what is returned if true.

    第一部分之后? 如果为true,返回什么
  • The second part after the : will be what is returned if false.

    之后的第二部分:,如果假返回的值

三元运算符的交互示例 ( Interactive Example of a Ternary Operator )

Here we have a CodePen similar to the earlier examples. Feel free to play around with this and see how we can use JavaScript ternary operators.

在这里,我们有一个与前面的示例类似的CodePen。 随意使用它,看看如何使用JavaScript三元运算符。

多线三元运算符 ( Multi-Line Ternary Operator )

If you need extra room and your ternary is getting too long for a single line (I like keeping an 80 character limit), you can split ternary statements to multiple lines.

如果您需要额外的空间并且三元数对于单行来说太长了(我喜欢保持80个字符的限制),则可以将三元数语句拆分为多行。

const howCoolAmI = name === 'chris' 
                                ? 100 
                                : 999 ;

关于命名的注意事项 ( A Note About Naming )

Ternary operators are just an operator that accepts 3 parts. What we've used throughout this article is just a conditional operator with 3 parts and that's why it's often referred to as the ternary operator. This is fine since JavaScript has only one operator that accepts 3 operands.

三元运算符只是接受3个部分的运算符。 我们在本文中使用的只是一个条件操作符,该操作符分为三部分,这就是为什么它通常被称为三元操作符的原因。 这很好,因为JavaScript只有一个运算符可以接受3个操作数。

翻译自: https://scotch.io/tutorials/javascript-ternary-operators