javascript语法糖

by Ryan Yurkanin

瑞安·尤卡宁(Ryan Yurkanin)

语法糖和JavaScript糖尿病 (Syntactic Sugar and JavaScript Diabetes)

Syntactic sugar is shorthand for communicating a larger thought in a programming language.

语法糖是用编程语言传达更大思想的简写。

I like to compare it to acronyms in natural languages. At first, seeing a new acronym can be confusing, but once you know what it means it’s way faster!

我喜欢将其与自然语言中的首字母缩写进行比较。 起初,看到一个新的缩写可能会造成混淆,但是一旦您知道它的含义,它就会更快!

With syntactic sugar - like with acronyms - you can GTFAMLH! (go too far and make life harder)

使用语法糖(如首字母缩写词),您可以GTFAMLH! (走得太远,使生活更艰难)

I was fresh out of college, making fun apps at hackathons with my friends, and on a newbie JavaScript thrill ride. I felt unstoppable. I understood all the Codecademy examples, I committed every front end interview question to memory. I watched “What the… JavaScript?” so many times that if a rampaging monkey scream-slammed random lines of code into a console, I knew what it would evaluate to.

我刚从大学毕业,就在与朋友一起的黑客马拉松上开发了有趣的应用程序,并开始了JavaScript新手之旅。 我感到势不可挡 。 我了解所有Codecademy示例,并把每个前端面试问题都记录下来了。 我看了“什么……JavaScript?” 如此多次,以至于如果一只狂暴的猴子在控制台中猛烈抨击随机的代码行,我就会知道它的结果。

It was time for me to get on GitHub, and share my gift with the world. I opened up the first project I could find, and started reading. It looked something like this:

现在是我进入GitHub并与世界分享我的礼物的时候了。 我打开了我可以找到的第一个项目,并开始阅读。 它看起来像这样:

function init(userConfig) {const DEFAULT_CONFIG = {removeSpaces: false,allowHighlighting: true,priority: "high",}const config = { ...DEFAULT_CONFIG, ...userConfig };
}

Moments later…

过了一会儿...

Confused and defeated, I closed out the browser tab and quit for the day. This would begin a chain of me doing the following:

感到困惑和失败,我关闭了浏览器选项卡,退出了这一天。 这将使我开始做以下事情:

  1. Discover a line of code which at the time was just JavaScript hieroglyphics.发现一行当时只是JavaScript象形文字的代码。
  2. Not knowing how to ask the right questions, and crafting quite possibly the worst Google searches known to humankind.不知道如何提出正确的问题,并且很可能制造人类已知的最糟糕的Google搜索。
  3. Bothering random developers until someone could “Explain Like I’m 5,” but in the end, still being confused why someone would write something like that. Sadism, probably.

    困扰着随机开发人员,直到有人可以“像我5岁时一样解释”,但最后,仍然困惑于为什么有人会写这样的东西。 虐待狂, 大概

4. Having it click, getting why it’s useful, understanding what problem it solves, and understanding what people did in the past to solve the problem. It was just a more concise way of writing code! It’s just sugar!

4.单击它,了解为什么有用,了解它可以解决什么问题,以及了解人们过去为解决该问题所做的事情。 这只是编写代码的一种更简洁的方式! 只是糖!

5. Sometimes, using it way too much and making my code subjectively worse.

5.有时候,用它的方式 太多,使我的代码在主观上更糟。

6. Finding the balance, and adding a great tool to my JavaScript toolkit. ?

6.找到平衡,并在我JavaScript工具箱中添加一个很棒的工具。 ?

5. Rinse and repeat about 20 times.

5.冲洗并重复约20次。

Now I’m here to try and break it down simply for you! For each sugary trick, I’ll include some backstory, a problem it could help solve, how you could achieve it before the syntactic sugar, and situations where you may not want to use it! ?

现在,我在这里为您尝试将其分解! 对于每个含糖的技巧,我都会介绍一些背景知识,可以帮助解决的问题,在语法糖之前如何实现它以及不希望使用它的情况! ?

三元运算符 (Ternary Operator)

The Ternary Operator is one of my favorite ones to start with when talking about sugar in JavaScript, since it’s really easy to go too far. It normally takes the form of x ? a : b. Here’s a more realistic example:

在谈论JavaScript中的糖时,三元运算符是我最喜欢的运算符之一,因为这样做太容易了。 通常采用x ? a : b的形式x ? a : b x ? a : b 。 这是一个更实际的示例:

const amILazy = true;
const dinnerForTonight = amILazy ? "spaghetti" : "chicken";

Problem: I have a variable that depends on some condition being true or false.

问题:我有一个变量,取决于某些条件为真还是假。

Diet Solution: This is basically just a really shorthand way to do an if/else!

饮食解决方案:基本上,这只是进行if/else一种非常简便的方法!

const amILazy = true;
let dinnerForTonight = null;if(amILazy) { dinnerForTonight = "spaghetti"; }
else { dinnerForTonight = "chicken"; }

When not to use it: Ternaries are a very simple way to express branching paths. In my subjective opinion, the worst thing about them is that they are infinitely nestable. So, if you’re a fan of job security, you could potentially write this brain melter.

什么时候不使用它:三元是表达分支路径的一种非常简单的方法。 以我的主观观点,关于它们的最糟糕的事情是它们是无限可嵌套的。 因此,如果您是工作安全的忠实拥护者,则可以编写这款“大脑熔化器”。

const canYouFireMe = someCondition1 ?(someCondition2 ? false : true) : false

Classic example of JavaScript Diabetes. Less code does not mean more concise code.

JavaScript Diabetes的经典示例。 更少的代码并不意味着更简洁的代码。

对象传播 (Object Spread)

Ah, the example from the beginning that broke my heart. In Javascript, when you see ..., depending on context it’s going to be Object/Array Spread, or Object/Array Rest. We are going to cover Rest in a bit, so let’s put that on the back burner.

啊,一开始的例子让我很伤心。 在Javascript中,当您看到...取决于上下文,它将是“对象/数组扩展”或“对象/数组其余部分”。 我们将稍微介绍一下Rest,所以我们把它放在后面。

Spreading is basically taking a single object, pulling all of its key/value pairs out, and putting them into another object. Here’s a basic example of spreading two objects into a new object:

扩散基本上就是将一个对象,将其所有键/值对拉出,然后将它们放入另一个对象。 这是将两个对象分散到一个新对象中的基本示例:

const DEFAULT_CONFIG = {preserveWhitespace: true,noBreaks: false,foo: "bar",
};const USER_CONFIG = {noBreaks: true,
}const config = { ...DEFAULT_CONFIG, ...USER_CONFIG };
// console.log(config) => {
//   preserveWhitespace: true,
//   noBreaks: true,
//   foo: "bar",
// }

Problem: I have an object, and I want to make another object that has all the same keys, with all the same values. Perhaps I want to do that with multiple objects, and if there are duplicate keys, choose which object’s keys win out.

问题:我有一个对象,并且想要创建另一个具有所有相同键且具有相同值的对象。 也许我想对多个对象执行此操作,如果有重复的键,请选择哪个对象的键胜出。

Diet solution: You could use Object.assign() to achieve a similar effect. It takes any number of objects as arguments, gives priority to the right-most objects when it comes to keys, and ends up mutating the very first object given. A common error is not passing in an empty object as the first argument and accidentally mutating an argument you didn’t mean to.

节食解决方案:您可以使用Object.assign() 达到类似的效果 。 它使用任意数量的对象作为参数,在涉及键时将优先级赋予最右边的对象,最后导致给定的第一个对象发生突变。 一个常见的错误是没有将空对象作为第一个参数传递,并且意外地改变了您本不想使用的参数。

If that’s hard to follow, you’ll be happy to know that Object Spread makes that impossible. Here’s an example that replicates the syntactic sugar version.

如果很难做到这一点,您将很高兴知道Object Spread使之成为不可能。 这是一个复制语法糖版本的示例。

const DEFAULT_CONFIG = {preserveWhitespace: true,noBreaks: false,foo: "bar",
};const USER_CONFIG = {noBreaks: true,
}// if we didn't pass in an empty object here, config
// would point to DEFAULT_CONFIG, and default config would be
// mutated
const config = Object.assign({}, DEFAULT_CONFIG, USER_CONFIG);

Object spread removes the chance for an accidental mutation. So you could do things, like update Redux State, without the fear of accidentally keeping a reference causing shallow comparison to fail.

对象传播消除了意外突变的机会。 因此,您可以执行更新Redux State之类的操作,而不必担心会意外保留引用,从而导致浅表比较失败。

? Bonus ? Array spread works very similarly! But since there aren’t any keys in arrays, it just kind of adds it to the new array like a Array.Prototype.concat call.

奖金? Ar ray传播的工作原理非常相似! 但是由于数组中没有任何键,它只是像Array.Prototype.concat调用那样将其添加到新数组中。

const arr1 = ['a', 'b', 'c'];
const arr2 = ['c', 'd', 'e'];
const arr3 = [...arr1, ...arr2];
// console.log(arr3) => ['a', 'b', 'c', 'c', 'd', 'e']

对象分解 (Object Destructuring)

This one I see pretty commonly out in the wild. Now, we have our new config object from the previous example, and want to use it in our code. You may see something like this scattered about the codebase.

我在野外很常见。 现在,我们有了上一个示例中的新配置对象,并希望在我们的代码中使用它。 您可能会在代码库中看到类似这样的内容。

const { preserveWhiteSpace, noBreaks } = config;// Now we have two new variables to play around with!
if (preservedWhitespace && noBreaks) { doSomething(); };

Problem: Having to write out the whole path to a key in an object can get pretty heavy, and clog up a lot of the code. To be more concise, it would be better to make a variable out of the value to keep the code neat.

问题:必须写出对象中键的整个路径可能会很繁重,并且会阻塞很多代码。 为了更简明扼要,最好使该变量超出该值,以使代码保持整洁。

Diet Solution: You can always do it the old fashioned way! That would look something like this.

饮食解决方案:您总是可以用老式的方式来做! 看起来像这样。

const preserveWhitespace = config.preserveWhitepsace;
const noBreaks = config.noBreaks;
// Repeat forever until you have all the variables you needif (preservedWhitespace && noBreaks) { doSomething(); };

When not to use it: You can actually destructure an object out of an object, and continue to destructure deeper and deeper! Destructuring isn’t the only way to get a key out of an Object. If you find yourself only using destructuring for keys two or three layers deep, chances are you are doing more harm than good to the project.

什么时候不使用它:您实际上可以从一个对象中分解出一个对象,并继续将其分解得越来越深! 解构并不是从对象中获取密钥的唯一方法。 如果您发现自己仅对两到三层的密钥使用了分解,那么对项目的危害可能大于弊端。

javascript语法糖_语法糖和JavaScript糖尿病相关推荐

  1. javascript写字技巧_网站建设对JavaScript书写如何更加规范化

    <网站建设对JavaScript书写如何更加规范化>由[张国维博客]于2017年10月23日整理发布! 网站建设注重与html分离, 减小reflow, 注重性能(function).库引 ...

  2. Java中语法分析器_语法分析器(java语法分析器)

    亲这是一款采用递归下降语法分析器,是一种适合手写语法编译器的方法,且非常简单.递归下降法对语言所用的文法有一些限制,但递归下降是现阶段主流的语法分析方法,因为它可以由开发人员高度控制,在提供错误信息方 ...

  3. javascript编程题_如何开始使用JavaScript进行竞争性编程

    javascript编程题 by Priyabrata Biswas 通过Priyabrata Biswas 如何开始使用JavaScript进行竞争性编程 (How to get started w ...

  4. 语法转换_语法 | 句型转换之肯定句变否定句

    0 1 谓语动词(组)中有be动词或者助动词时 直接在第一个动词后面加not. Eg: I am a teacher.--I am not a teacher. (有be动词) She is my s ...

  5. 语法转换_语法干货|直接引语转换间接引语的方法指导,还不会用的赶紧收藏了!...

    直接引语和间接引语 引述某人的话一般采用两种形式: 一种是直接引语(Direct Speech),即原封不动地引用原话,把它放在引号内: 另一种是间接引语(Indirect Speech),即用自己的 ...

  6. 语言语法糖_【c#】几种常用语法糖

    语法糖(syntactic sugar)是由英国计算机科学家Peter J. Landin发明的术语,指计算机语言中添加的某种语法.这种语法不影响语言的功能,但更方便使用. 在开发中使用语法糖能够让程 ...

  7. python装饰器语法糖_最全python装饰器的各种写法

    装饰器是最容易在我们项目编写上出现的内容,结实的掌握这部分内容,对我们的代码是否能顺利编写时非常重要的,下面就关于python装饰器问题,给大家最详细介绍. 装饰器的示例代码# 定义装饰器 def d ...

  8. JavaScript进阶篇①——基础语法

    一.认识JS 你知道吗,Web前端开发师需要掌握什么技术?也许你已经了解HTML标记(也称为结构),知道了CSS样式(也称为表示),会使用HTML+CSS创建一个漂亮的页面,但这还不够,它只是静态页面 ...

  9. 几个有趣的名词--语法糖、语法盐等

    今天看<Java NIO>,里边出现"语法糖"这一名词,觉得挺有趣就问google,结果出来连带了其他几个类似名词,这里仅作整理. 语法糖 语法糖(Syntactic ...

最新文章

  1. 十年“老司机”的私家锦囊:10个编程技巧、5个纠错步骤,让你的编程之路少点坎坷
  2. matplotlib画图、如何提高图像分辨率?
  3. Apache日志配置参数说明
  4. 红帽Redhat6.4 iso下载地址
  5. hdu_2227_Find the nondecreasing subsequences_树状数组,离散化
  6. Java agent初探
  7. 何小鹏“维权”事后谈造车:心很累 曾购上千瓶白酒缓解压力
  8. 增强 for 循环 和 普通for 循环的 区别总结
  9. oracle12c 常用视图,oracle12c v$sql视图字段全解
  10. 计算机网络cs144之lab0
  11. C语言中文网 读后感
  12. 如何培养自己的商业思维能力?
  13. 大数据为我们的生活带来了什么?
  14. 设计模式的六大原则(SOLID)
  15. 全球最牛掰的 14 位大神,你知道几个??
  16. foxmail收件箱按照每个人进行划分
  17. Spring注入bean报错:Error creating bean with name的网上找不到的解决方案
  18. c语言输入姓名查分数,输入学生姓名,查找该学生并输出其学号姓名成绩
  19. 2020/8/3/ATC工具以及AIPP
  20. 榜单预告!4D成像/点云毫米波雷达进入量产年,谁能进入TOP10

热门文章

  1. 《深入理解计算机系统》学习心得二:关于show-bytes的 学习
  2. android 开启一个定时线程_ANDROID开发中定时器的3种方法
  3. 电力系统稳定与控制_基于数据驱动的电力系统稳定性分析
  4. ai为什么要栅格化_三大优势告诉你,为什么一定要加盟AI定制家居
  5. 微信小程序用户未授权bug解决方法,微信小程序获取用户信息失败解决方法
  6. 1-flutter 安装步骤
  7. 使用Silverlight2的WebClient下载远程图片
  8. Distinction Between Strategy and Decorator
  9. Swift3.0带来的变化汇总系列一——字符串与基本运算符中的变化
  10. 【Swift】 GETPOST请求 网络缓存的简单处理