当前位置: 首页 > 编程日记 > 正文

初步了解:使用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/

相关文章:

div 下 的img水平居中

设置text-align:center; 这个div必须要设置宽度&#xff1b; 如&#xff1a;{text-align:center; width:100%;}转载于:https://www.cnblogs.com/zzd0916/p/6626772.html

Understanding SOAP

Understanding SOAP转载于:https://www.cnblogs.com/daishuguang/p/4227983.html

js删除组数中的某一个元素(完整代码附效果图)

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 正文&#xff1a; <view class"big-logos"> <imagebindtap"addimg"src../../../image/s.png></image> <blockwx:for"{{img_arr}}"wx:key"in…

c专家编程/c陷阱_如何避免常见的初学者陷阱并像专家一样开始编码

c专家编程/c陷阱by Dmitri Grabov德米特里格拉波夫(Dmitri Grabov) 如何避免常见的初学者陷阱并像专家一样开始编码 (How to avoid common beginner pitfalls and start coding like a pro) Learning to code is tough. We’ve all encountered cryptic errors and code break…

xmpp关于后台挂起的消息接收,后台消息推送,本地发送通知

想问下&#xff0c;在xmpp即时通讯的项目中&#xff0c;我程序如果挂起了&#xff0c;后台有消息过来&#xff0c;我这边的推送不过来&#xff0c;所以我的通知就会收不到消息&#xff0c;当我重新唤醒应用的时候&#xff0c;他才会接收到通知&#xff0c;消息就会推送过来&…

[冲昏头脑]IDEA中的maven项目中学习log4j的日志操作

第一&#xff0c;你要有log4j的对应的包&#xff0c;由于我用的maven&#xff0c;所以直接在pom.xml文件依赖下载则可&#xff0c;如你尚为有此包&#xff0c;请自行百度下载导入&#xff0c;或上http://www.mvnrepository.com/搜索。上如则是我的log4j的包的版本。好了&#x…

女神推荐, 卡片,广告图 ,点击查看更多

微信小程序开发交流qq群 581478349 承接微信小程序开发。扫码加微信。 正文&#xff1a; <view><view classtitle>女神推荐 </view> <image stylemargin-top:25rpx; classtab_img src{{img list_data.q1[1].image}}></image><view classv…

aws lambda_恐怕您正在考虑AWS Lambda的冷启动完全错误

aws lambdaby Yan Cui崔燕 恐怕您正在考虑AWS Lambda的冷启动完全错误 (I’m afraid you’re thinking about AWS Lambda cold starts all wrong) When I discuss AWS Lambda cold starts with folks in the context of API Gateway, I often get responses along the line of…

python tkinter窗口弹出置顶的方法

加上下面两句即可实现root窗口的置顶显示&#xff0c;可以用于某些程序的消息提示&#xff0c;能够弹出到桌面显示 root Tk() root.wm_attributes(-topmost,1) 转载于:https://www.cnblogs.com/shuchengxiang/p/6632140.html

用Quartus II Timequest Timing Analyzer进行时序分析 :实例讲解 (一)

一&#xff0c;概述 用Altera的话来讲&#xff0c;timequest timing analyzer是一个功能强大的&#xff0c;ASIC-style的时序分析工具。采用工业标准--SDC&#xff08;synopsys design contraints&#xff09;--的约束、分析和报告方法来验证你的设计是否满足时序设计的要求。在…

软件工程与软件测试基础知识_这是我在软件工程工作九个月中学到的知识

软件工程与软件测试基础知识I’ve been working for about nine months at Dexter as a software developer. I wrote a blog post about landing the job initially, as well as a technical post about a self positioning component I made in my first couple of months at…

[bzoj1064][Noi2008]假面舞会

题意:有n个人&#xff0c;每个人都有一个标号&#xff0c;每种标号的人只能看见下一个标号的人&#xff08;最后一种标号看见第一种&#xff09;&#xff0c;给定m个关系&#xff0c;求这个关系是否合法以及合法情况下最大和最小的方案数。$n\leqslant 10^{5},m\leqslant 10^{6…

js取一定范围内的随机整数

Math.floor(Math.random()*305 1); Math.random()*305 的作用是取0到305的随机数 加1 就是1到305的随机数, Math.floor是取整数, 所以最后的结果是0到305的随机整数 微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。

AE,按照属性值关系选择要素

if(axMapControl2.LayerCount<0) { MessageBox.Show("请加载图层后使用该功能","系统提示",MessageBoxButtons.OK,MessageBoxIcon.Warning); } else { ILayer pLayer axMapControl2.get_Layer(0); IFeatureLayer pFeatureLayer pLayer as IFeatureLay…

aws lambda使用_如何使用AWS Lambda和S3构建无服务器URL缩短器

aws lambda使用by Daniel Ireson丹尼尔埃里森(Daniel Ireson) 如何使用AWS Lambda和S3构建无服务器URL缩短器 (How to build a Serverless URL shortener using AWS Lambda and S3) Throughout this post we’ll be building a serverless URL shortener using Amazon Web Ser…

android -volley-请求数据

private List<gson.DataBean>arrGson;//请求的数据 //请求数据的方法 public void initData() { RequestQueue mQueue Volley.newRequestQueue(getApplicationContext()); String url "http://www.fashions88.com/you/HBooks88/GetBooks88Data…

[微信小程序]动画,从顶部掉花的效果(完整代码附效果图)

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 正文&#xff1a; image{ width: 100rpx;height: 100rpx;position: absolute;top: -100rpx; } 如果对您有帮助&#xff0c;请关注我&#xff0c;欢迎加入微信小程序开发交流QQ群&#xff08;173683866&…

pl/sql developer连接远程数据库

本地不安装oracle client程序&#xff0c;直接使用pl/sql developer连接远程数据库 考虑到机子本身资源有限&#xff0c;一个client会占用很多资源&#xff0c;尝试使用不安装客户端的方式进行远程连接。 需要软件&#xff1a;instantclient-basic-win32-10.2.0.5.zip、pl/sql …

工厂用抽象类比接口_用简单的现实类比解释硬编码概念

工厂用抽象类比接口by Samer Buna通过Samer Buna 用简单的现实类比解释硬编码概念 (Hard Coding Concepts Explained with Simple Real-life Analogies) 如何向5岁的孩子解释诸如流&#xff0c;promise&#xff0c;lint和声明性编程之类的编码概念 (How to explain coding con…

[微信小程序]点击切换卡片动画效果

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 正文&#xff1a; 先上效果图, GIF: <!--pages/roll/roll.wxml--> <!-- 单身 --> <block wx:if"{{danshen}}"><view class"card_wrap"><view animatio…

redis学习之——Redis事务(transactions)

Redis事务&#xff1a;可以一次执行多个命令&#xff0c;本质是一组命令的集合。一个事务中的&#xff0c;所有命令都会序列化&#xff0c;按顺序地串行化执行而不会被其它命令插入&#xff0c;不许加塞。 常用命令&#xff1a;MULTI 开启事务 EXEC 提交事务、 DISCARD 放弃…

WordPress页面Page和文章Post的相互转换

1. 进入phpMyAdmin&#xff1b; 2. 进入WordPress对应的数据库&#xff1b; 3. 浏览wp_posts数据表&#xff1b; 4. 找到相应的 页面Page 并编辑&#xff08;找到相应的 文章Post 并编辑&#xff09;&#xff1b; 5. 修改 post_type 为 post&#xff08;page&#xff09;&#…

airbnb_我如何在一个晚上建立音乐工作室的Airbnb

airbnbby Mike Williams由Mike Williams 我如何在一个晚上建立音乐工作室的Airbnb (How I built the Airbnb of music studios in a single evening) Sometimes you come up with an idea that you just know has to be built. That was the case I came up with Studiotime, …

QT学习第8课:QT计算器界面实现

声明&#xff1a;此文章仅是个人在学习狄泰QT课程所做的笔记&#xff0c;文章中包含狄泰资料的&#xff0c;一切版权归狄泰软件所有&#xff01;   第8课是来做一个计算器界面&#xff0c;只是一个界面显示。不过也是挺兴奋的&#xff0c;以前一直对着黑框框&#xff0c;现在…

C# 实现对接电信交费易自动缴费 续(winio/winring0 自动填密码)

自动填密码大家可能都不莫生,最有名的应该是 按键精灵 只要是一个可以输入的地方都可以能过按键精灵来完成输入.我今天要讲的是使用 winio/winring0来完成类似的功能 如果要自动填充密码方式基本上有 消息级的模拟 和 驱动级的模拟, 消息级的模拟如 C# 直接使用 SendKeys 就可以…

[微信小程序]js动态改变数组对象列表中的样式

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 正文&#xff1a; 这里我用微信小程序商城开发中选择商品规格选择做示例: 先把效果图让大家看看, 默认情况下是这样的 当点击了规格11以后: 该商品规格的颜色变成红色,并且显示该规格商品的图片和…

ios snapkit m_如何使用自动布局和SnapKit在iOS上创建漂亮的拉伸布局

ios snapkit mby Enabled Solutions由Enabled Solutions 如何使用自动布局和SnapKit在iOS上创建漂亮的拉伸布局 (How to create beautiful Stretchy Layouts on iOS using Auto Layout and SnapKit) Check the image below. This is a cool effect.检查下面的图像。 这是一个很…

谷歌 notification 测试 页面

1 <button onclick"notifyMe(master wei,http://cdn.sstatic.net/stackexchange/img/logos/so/so-icon.png,我在测试谷歌通知功能,http://www.mi.com/)">通知!</button>2 <script>3 var sum 0;4 document.addEventListener(DOMContentLoaded, fun…

[转]如果我有jQuery背景,我应该如何切换到AngularJS的思维模式?

导言 stackoverflow上有一个人问了一个问题&#xff1a;如果我有jQuery背景&#xff0c;我应该如何切换到AngularJS的思维模式&#xff1f; 有一个回复非常经典&#xff0c;获得了两千多票。 为了让国内开发者也能领略到其中的核心思想&#xff0c;现把这个问题和答案翻译出来供…

[微信小程序]实现一个自定义遮罩层组件(完整示例代码附效果图)

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 正文&#xff1a; 先上效果图: 点击按钮Show显示遮罩层,再次点击屏幕任何地方隐藏遮罩层; <button bindtap"showview">Show</button> <view class"bg" bindtaphide…