JavaScript三元运算符

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;

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值