初步了解:使用JavaScript进行表达式(De Do Do Do,De Da Da Da)

by Donavon West

由Donavon West

初步了解:使用JavaScript进行表达式(De Do Do Do,De Da Da Da) (A first look: do expressions in JavaScript (De Do Do Do, De Da Da Da))

This article is not about about the The Police’s 1980 hit song from album Zenyatta Mondatta (although that would be awesome!) No, it’s about the T39 proposal called do expressions. If approved by TC39, “do expressions” will be part of JavaScript and could help usher your code out of ternary hell.

本文不是关于专辑Zenyatta Mondatta的The Police 1980热门歌曲(尽管那太棒了!)不这是关于T39提案do expressions的 。 如果得到TC39的批准,“ do expressions”将成为JavaScript的一部分,并且可以帮助将您的代码引向三元地狱。

Do expressions allow you to embed a statement inside of an expression. The resulting value is returned from the expression.

Do表达式允许您将语句嵌入表达式内部。 结果值从表达式返回。

It’s currently in what is called “stage 1” of the TC39 process, which means that do expressions have a long way to go before they see the light of day.

当前处于TC39流程的“阶段1”中,这意味着表达式要走很长的路要走。

Axel Rauschmayer explains the TC39 process in his book titled Exploring ES2016 and ES2017 (free online, or purchase the eBook).

Axel Rauschmayer在他的书《 探索ES2016和ES2017》 (免费在线或购买电子书)中解释了TC39流程

什么是表达? (What is a do expression?)

Here is a simple example of a simple do expression.

这是一个简单的do表达式的简单示例。

const status = do {  if (isLoading) {    'Loading';  } else if (isError) {    'Error'  } else {    'Running'  };};

It takes whatever is “returned” as the value of the statement and assigns it to status. Not very useful over a basic if statement, IMO.

它使用“返回”的任何内容作为语句的值并将其分配给status 。 对于基本的if语句,IMO不是很有用。

Where it really shines is when used within JSX in a React application.

真正令人瞩目的地方是在React应用程序的JSX中使用时。

在JSX中使用 (Use in JSX)

Do expressions are especially useful within JSX. Let’s take a look at how you might use them for a common React pattern in the context of JSX: determining what to render based on loading and error props.

Do表达式在JSX中特别有用。 让我们看一下如何在JSX上下文中将它们用于常见的React模式:根据loadingerror道具确定要呈现的内容。

const View = ({ loading, error, ...otherProps }) => (  <;div>    {do {      if (loading) {        <Loading />      } else if (error) {        <Error error={error} />      } else {        <MyLoadedComponent {...otherProps} />      };    }}  </div>);

Wow! Now that’s incredibly powerful.

哇! 现在,它非常强大。

The same thing could be performed with a logical AND statement, but you end up negating all of the other values. This can get pretty messy, and is rather hard to follow. It’s also not as efficient from an execution perspective, as this is roughly equivalent to performing three if statements.

可以使用逻辑AND语句执行相同的操作,但最终会否定所有其他值。 这会变得非常混乱,并且很难遵循。 从执行角度来看,它也不是很有效,因为它大致等效于执行三个if语句。

const View = ({ loading, error, ...otherProps }) => (  <;div>    {loading && !error &&      <Loading />    }    {!loading && error &&      <Error error={error} />    }    {!loading && !error &&      <MyLoadedComponent {...otherProps} />    }  </div>);

什么是三元地狱? (What is ternary hell?)

For a little background, a ternary is a JavaScript operator that accepts three operands: a condition, followed by two expressions. It is often used to replace an if statement.

出于某种背景, 三元是JavaScript运算符,它接受三个操作数:一个条件,后跟两个表达式。 它通常用于替换if语句。

Here is an example of a ternary operator in action.

这是一个使用三元运算符的示例。

const text = isLoading ? 'Loading' : 'Loaded';

The variable text is set to “Loading” or “Loaded” depending on the isLoading binary flag. This is roughly equivalent to the following if statement.

根据isLoading二进制标志,将变量text设置为“ Loading”或“ Loaded”。 这大致等效于以下if语句。

let text;
if (isLoading) {  text = 'Loading';} else {  text = 'Loaded';}

However, notice that we need to use a let statement vs. a const. You can see that a ternary is a great way to reduce clutter from your code, plus it allows you to avoid using an unnecessary let statement in lieu of a const.

但是,请注意,我们需要使用let语句和const 。 您会发现三元是减少代码混乱的好方法,而且它还使您避免使用不必要的let语句代替const

I see let statements as a red-flag when I’m doing code reviews. Same thing with if statements.

在执行代码审查时,我将let语句视为一个危险信号。 与if语句相同。

But what if we have a non-binary value? You might combine ternaries and end up with something like this.

但是,如果我们具有非二进制值呢? 您可能会合并三元并最终得到这样的结果。

const text =   stopSignColor === 'red'     ? 'Stop' :  stopSignColor === 'yellow'     ? 'Caution' :  stopSignColor === 'green'     ? 'Go' :  'Error';

This is what I’m referring to when I say ternary hell.

当我说三元地狱时,这就是我所指的。

It’s a kind of if/else if/else if/else statement written using a ternary. Many people find this form hard to follow. In fact, you can even prevent this behavior with an ESLint no-nested-ternary setting.

这是一种使用三进制编写的if/else if/else if/else语句。 许多人觉得这种形式很难遵循。 实际上,您甚至可以使用ESLint no-nested-ternary设置来防止此行为。

Here’s the same code written using a switch statement embedded within a do expression.

这是使用嵌入在do表达式中的switch语句编写的相同代码。

const text = do {  switch (stopSignColor) {  case 'red': 'Stop'  case 'yellow': 'Caution'  case 'green': 'Go'  case default: 'Error'  }};

未来是现在 (The future is now)

Even though do expressions are not officially part of the language (yet?), you can still use them now in your project. This is because most of us don’t really code in JavaScript — we code in Babel. And luckily, there’s a Babel transform that will bring us tomorrow’s language syntax today.

即使表达式不是语言的正式组成部分(尚未?),您现在仍可以在项目中使用它们。 这是因为我们大多数人实际上并不是使用JavaScript编写代码,而是使用Babel编写代码。 幸运的是, Babel转换将带给我们今天明天的语言语法。

But be careful when choosing this option. There’s no guarantee that the proposal will pass as-is. The specification may dramatically change, leaving your code in need of some re-factoring. In fact, it’s entirely plausible that the specification could be dropped all-together.

但是选择此选项时要小心。 不能保证提案会原样通过。 规范可能会发生巨大变化,从而使您的代码需要进行一些重构。 实际上,完全放弃该规范是完全合理的。

结论 (Conclusion)

Do expressions have their place, but are hardly a silver bullet. With the help of a Babel transform, they can be used today. One of the greatest benefits of do expressions is when used from within JSX.

表达式有自己的位置,但不是万能的。 借助Babel变换,它们可以立即使用。 do表达式的最大好处之一是在JSX中使用。

And that’s “all I want to say to you”.

那就是“我想对你说的一切”。

I also write for the American Express Engineering Blog. Check out my other works and the works of my talented co-workers at AmericanExpress.io. You can also follow me on Twitter.

我也为《美国运通工程博客》撰文。 在AmericanExpress.io上查看我的其他作品和我的才华横溢的同事的作品。 您也可以在Twitter上关注我

翻译自: https://www.freecodecamp.org/news/a-first-look-do-expressions-in-javascript-de-do-do-do-de-da-da-da-fc87f5fe238a/

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值