javascript语法糖_语法糖和JavaScript糖尿病
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:
感到困惑和失败,我关闭了浏览器选项卡,退出了这一天。 这将使我开始做以下事情:
- Discover a line of code which at the time was just JavaScript hieroglyphics.发现一行当时只是JavaScript象形文字的代码。
- Not knowing how to ask the right questions, and crafting quite possibly the worst Google searches known to humankind.不知道如何提出正确的问题,并且很可能制造人类已知的最糟糕的Google搜索。
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.
什么时候不使用它:您实际上可以从一个对象中分解出一个对象,并继续将其分解得越来越深! 解构并不是从对象中获取密钥的唯一方法。 如果您发现自己仅对两到三层的密钥使用了分解,那么对项目的危害可能大于弊端。
🎉 Bonus 🎉 Arrays also have destructuring, but they work based off index.
🎉奖励🎉数组也具有解构性,但是它们基于索引工作。
const arr1 = ['a', 'b']
const [x, y] = arr1
// console.log(y) => 'b'
物体休息 (Object Rest)
Object Rest goes hand in hand with Object Destructuring, and is very easy to confuse with Object Spread. Once again we use the ...
operator, however the context is different. This time, it shows up while destructuring and is intended to gather leftover keys into one object. ?
Object Rest与Object Destructuring紧密相关,并且很容易与Object Spread混淆。 再次使用...
运算符,但是上下文不同 。 这次,它在销毁时显示,旨在将剩余的键收集到一个对象中。 ?
const { preserveWhiteSpace, noBreaks, ...restOfKeys } = config;// restOfKeys, is an object containing all the keys from config
// besides preserveWhiteSpace and noBreaks
// console.log(restOfKeys) => { foo: "bar" }
Problem: You want an object that has a subset of keys from another object.
问题:您想要一个对象,该对象具有另一个对象的键子集。
Diet Solution: You could use our old pal Object.assign
and delete any of the keys that you don’t need! ?
Diet解决方案:您可以使用我们的老朋友Object.assign
并删除不需要的任何键! ?
When not to use it: Using it to create a new object with omitted keys is a common use case. Just be aware that the keys you are omitting in the destructure are still floating around and potentially taking up memory. If you’re not careful, this could cause a bug. ?
何时不使用它:用它创建具有省略键的新对象是一种常见的用例。 请注意,您在解构中省略的键仍在浮动,并可能占用内存。 如果不小心,可能会导致错误。 ?
const restOfKeys = Object.assign({}, config);
delete restOfKeys.preserveWhiteSpace
delete restOfKeys.noBreaks
🎉 Bonus 🎉 Guess what? Arrays can do something similar and it works exactly the same!
🎉奖金🎉你猜怎么着? 数组可以做类似的事情,并且工作原理完全一样!
const array = ['a', 'b', 'c', 'c', 'd', 'e'];
const [x, y, ...z] = array;
// console.log(z) = ['c', 'c', 'd', 'e']
结语 (Wrapping up)
JavaScript sugar is great, and understanding how to read it will allow you to enter more diverse code bases and expand your mind as a developer. Just remember that it’s a balancing act between actually being concise, and making your code readable for others and your future self.
JavaScript糖很棒,并且了解如何阅读它可以使您输入更多不同的代码库,并扩大您作为开发人员的思维。 只需记住, 这是在保持简洁与使代码对他人可读以及您自己的未来之间取得平衡。
While it might feel awesome showing off your shiny new tool, our job as programmers is to leave codebases more maintainable then they were when we entered them.
炫耀您闪亮的新工具可能让人感觉很棒,但是作为程序员,我们的工作是使代码库比我们输入代码库时更具可维护性。
Here’s a collection of the MDN Documents on what I covered if you want to do some further reading. ?
如果您想做进一步的阅读,这是MDN文档的集合,内容涉及我所介绍的内容。 ?
Ternary Operator
三元运算符
Spread Syntax
传播语法
Destructuring Assignment
销毁分配
Rest Parameters
休息参数
翻译自: https://www.freecodecamp.org/news/js-diabetes-and-understanding-syntax-sugar-5de249ee9ebc/
javascript语法糖
相关文章:

《DSP using MATLAB》示例Example7.23
代码: wp 0.2*pi; ws 0.3*pi; Rp 0.25; As 50; [delta1, delta2] db2delta(Rp, As);[N, f, m, weights] firpmord([wp, ws]/pi, [1, 0], [delta1, delta2]);N f m weightsh firpm(N, f, m, weights); [db, mag, pha, grd, w] freqz_m(h, [1]);delta_w 2*pi…

css画图笔记
微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 正文: 在网页中,经常会用到各种Icon,如果老是麻烦设计狮画出来不免有些不好意思,所以有时候我们也可以用CSS写出各种简单的形状,一来可以减轻…

Web前端开发最佳实践(8):还没有给CSS样式排序?其实你可以更专业一些
前言 CSS样式排序是指按照一定的规则排列CSS样式属性的定义,排序并不会影响CSS样式的功能和性能,只是让代码看起来更加整洁。CSS代码的逻辑性并不强,一般的开发者写CSS样式也很随意,所以如果不借助工具,不太容易按照既…

超越Android:Kotlin在后端的工作方式
by Adam Arold亚当阿罗德(Adam Arold) 超越Android:Kotlin在后端的工作方式 (Going Beyond Android: how Kotlin works on the Backend) This article is part of a series.本文是系列文章的一部分。 While most developers use Kotlin on Android, it is also a …

词汇的理解 —— 汉译英(术语)
词汇的理解 —— 英译汉 1. 名词 机制:mechanism,系统:system;2. 动词 融资:financing;制动:braking,就是“刹车”;3. 音乐与乐器 horn:喇叭,号角…

Swift从零开始学习_08(代理协议传值)
Swift中的代理协议的写法. 这是第一个页面有一个button和一个label, button点击跳到下一个页面. 第二个页面有一个输入框和一个按钮, 点击按钮把输入框里的内容设置为第一个页面label的内容.效果如下 接下来是代码部分.跟OC的写法还是一样的.这里不再写第一个页面的那些UI的…

[微信小程序]商城之购买商品数量实现
微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 正文: 这里有三种变更数量的方式, 加号,减号,input输入 , 这里做了限制,数量不能小于等于0并且不能超过现有库存,下面是…

测试nginx网站代码_在40行以下代码中使用NGINX进行A / B测试
测试nginx网站代码by Nitish Phanse由Nitish Phanse 在40行以下代码中使用NGINX进行A / B测试 (A/B testing with NGINX in under 40 lines of code) A/B Testing, has enabled designers and product managers to get a deep insight into user behavioral patterns.A / B测试…

HttpServletResponse,HttpServletRequest详解
HttpServletResponse,HttpServletRequest详解 1、相关的接口 HttpServletRequest HttpServletRequest接口最常用的方法就是获得请求中的参数,这些参数一般是客户端表单中的数据。同时,HttpServletRequest接口可以获取由客户端传送的名称,也可…

[微信小程序]this.setData , that.setData , this.data.val三者之间的区别和作用
微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 正文: 1.this.setData({ }) <view bindtouchmove"tap_drag" bindtouchend"tap_end" bindtouchstart"tap_start" class"page-top" style"{…

jQuery(一)引入
一、jQuery简介 jQuery是一个兼容多浏览器的javascript库,核心理念是write less,do more(写得更少,做得更多) 二、安装 2.1、下载 下载地址:http://jquery.com/download/ 2.2、引入 在页面头部加入 <head> <meta http-equiv"Content-Type&…

javascript 堆栈_JavaScript调用堆栈-它是什么以及为什么它是必需的
javascript 堆栈The JavaScript engine (which is found in a hosting environment like the browser), is a single-threaded interpreter comprising of a heap and a single call stack. The browser provides web APIs like the DOM, AJAX, and Timers.JavaScript引擎(可在…

idea崩溃导致的svn插件丢失问题, maven dependencies视图丢失问题
Idea丢失Svn解决办法今天打开Idea,习惯用ctrlt来更新svn,杯具出现了,快捷键失效了,我觉得可能是其他的什么软件占用了这个快捷键,于是重启了一下,发现还是不行,svn信息怎么没了,chan…

python3代码
import urllib.request url"http://mm.taobao.com/json/request_top_list.htm?type0&page1" upurllib.request.urlopen(url)#打开目标页面,存入变量up contup.read()#从up中读入该HTML文件 key1<a href"http#设置关键字1key2"target&qu…

【微信小程序】侧滑栏,手动侧滑出个人中心(完整代码附效果图)
微信小程序开发交流qq群 581478349 承接微信小程序开发。扫码加微信。 正文: 博文分三部分,1.效果图及功能效果说明 2.实现思路 3.源代码 欢迎加入微信小程序开发交流群(173683895) 一.老惯例先上效果图,本篇博…

1:1 人脸比对 开源_Hacktoberfest:我的开源门户
1:1 人脸比对 开源by Maribel Duran通过Maribel Duran Hacktoberfest:我的开源门户 (Hacktoberfest: My Gateway to Open Source) “Individually, we are one drop. Together, we are an ocean.”“就个人而言,我们只是一滴滴。 在一起,我们…

地图收敛心得170405
寻路算法大总结! 交换机生成树采用的是完全不同的D-V(distance vector)距离矢量算法,并不是很可靠. 并不是任意两点之间的最短路径,因为任意两点之间取最短路径可能有环路:总权更大 交换机STP不一定是最小生成树!!!举例论证 因为它只是所有交换机到根桥最短 贪心算法的味道 kru…

微信小程序游戏开发文档以及开发工具地址
微信小程序开发交流qq群 581478349 承接微信小程序开发。扫码加微信。 正文: 微信官方于 2017 - 12 - 28 日 开发微信小程序 开发小游戏 , 微信小程序小游戏开发官方文档的地址 https://mp.weixin.qq.com/debug/wxagame/dev/index.html?t20171228…

c#编译执行过程
创建一个简单的控制台程序,源码如下: using System; using System.Collections.Generic; using System.Linq; using System.Text;namespace csharpBuildProcess {class Program{static void Main(string[] args){for (int i 0; i < 100; i){if(i%20)…

渐进式web应用程序_渐进式Web应用程序简介
渐进式web应用程序Interested in learning JavaScript? Get my ebook at jshandbook.com有兴趣学习JavaScript吗? 在jshandbook.com上获取我的电子书 Progressive Web Apps (PWA) are the latest trend in mobile application development using web technologies.…

第二百二十节,jQuery EasyUI,Slider(滑动条)组件
jQuery EasyUI,Slider(滑动条)组件 学习要点: 1.加载方式 2.属性列表 3.事件列表 4.方法列表 本节课重点了解 EasyUI 中 Slider(滑动条)组件的使用方法,这个组件依赖于 Draggable(拖动)组件。 一.加载方式 class 加载方式 <…

适用于SharePoint 2013 的 CAML Desinger
适用于SharePoint 2013 的 CAML Desinger 分类: SharePoint2013-01-15 21:52 1877人阅读 评论(0) 收藏 举报CAMLDesingerSharePoint 2013代码生成适用于如果说Sql是信息管理系统的一等公民,那么SharePoint 系统中的一等公民就非CAML莫属了。 但是这个一等…

微信小程序 跑马灯效果完整代码附效果图
微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 正文: 一:功能介绍及讲解 实现的跑马灯(跑马灯里面显示文章的title)的效果,并在右侧有个查看文章的按钮,按钮绑定当前的跑马灯信…

热闹的聚会与尴尬的聚会_如何增加(和保存)您最喜欢的技术聚会
热闹的聚会与尴尬的聚会by Jen Weber詹韦伯(Jen Weber) 如何增加(和保存)您最喜欢的技术聚会 (How to Grow (and Save) Your Favorite Tech Meetup) Hey meetup facilitators, friends, and future leaders! Do you want more people to show up to your tech event? Or at l…

蓝桥杯-搭积木-java
/* (程序头部注释开始) * 程序的版权和版本声明部分 * Copyright (c) 2016, 广州科技贸易职业学院信息工程系学生 * All rights reserved. * 文件名称: 蓝桥杯赛题 * 作 者: 彭俊豪 * 完成日期…

微信小程序多张图片和表单一起上传,验证表单及进度条的实现完整代码
微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 正文: 效果图: 完整代码: <!--pages/register/register.wxml--> <view classtop> <view>注 册 须 知 : </view> </view> <view> <view …

Android, BaseAdapter 处理大数据量时的优化
Android优化 最常见的就是ListView, Gallery, GridView, ViewPager 的大数据优化 图片优化 访问网络的优化优化的原则: 数据延迟加载 分批加载 本地缓存数据优化 1).复用contentview 2).创建static class ViewHolder 3).分…

meetup_我在2017年举办Meetup中学到的知识以及为何对2018年充满期待。
meetupby Daniel Deutsch由Daniel Deutsch 我在2017年举办Meetup中学到的知识以及为何对2018年充满期待。 (What I’ve learned hosting Meetups in 2017 — and why I’m looking forward to 2018.) As 2017 comes to an end, it’s time to reflect on the non-profit work …

BASE64 编码和解码
依赖jar: import org.apache.commons.codec.binary.Base64; BASE64和其他相似的编码算法通常用于转换二进制数据为文本数据,其目的是为了简化存储或传输。更具体地说,BASE64算法主要用于转换二进 制数据为ASCII字符串格式。Java语言提供了一个非常好的BA…

Android开发常用属性
1、android string.xml 文字中间加入空格 android string.xml前后加空格的技巧 <string name"password">密 码</string>   这个就代表着空格 2、文字单行显示 android layout布局文件中TextView、EditView单行显示和输入 <TextView androi…