javascript指南_熟练掌握JavaScript的指南

javascript指南

So you’re trying to learn JavaScript but are inundated with all the different syntax and ways to program that have evolved over time?

因此,您正在尝试学习JavaScript,但是却被随时间演变的所有不同语法和编程方式所淹没?

Why is that code littered with backticks? What in the world are these mysterious arrows, they look like someones introduced emoji’s? 3 dots, what the what?

为什么该代码充满了反引号? 这些神秘的箭头到底是什么,就像有人介绍的表情符号一样? 3点,那是什么?

Our industry consists of a mass of psychologically frayed individuals ever stressing about imposter syndrome and self doubt. “Will I be found out that I don’t know what I’m doing?”, “I haven’t a clue how this code works, it just seems to run with magic.” “I got nowhere yesterday and everyone is looking at me now in the daily scrum”. “I’m such a failure and everyone is doing better than I am”. Familiar?

我们的行业由一群精神错乱的个体组成,这些个体一直强调冒名顶替综合症和自我怀疑。 “ 是否会发现我不知道自己在做什么?”,“我不知道这段代码是如何工作的,它似乎很神奇。” “昨天我一无所获,现在每个人每天都在看着我。” “我是如此失败,每个人都比我做得更好 。” 熟悉吗?

In an environment where knowledge is power, we are ever the hamster on a learning treadmill just trying to outpace everyone else so we don’t look stupid in front of our peers. This lack of (my) knowledge became clear recently when I joined a front-end project comprised primarily of JavaScript code. I thought I knew JavaScript. I was completely wrong.

在知识就是力量的环境中,我们一直是学习型跑步机上的仓鼠,只是在努力超越其他所有人,因此我们在同行面前不会显得愚蠢。 最近,当我加入一个主要由JavaScript代码组成的前端项目时,这种(我)知识的匮乏就变得很明显。 我以为我知道JavaScript。 我完全错了。

You say, “Don’t you have to use the function keyword to declare functions?” (because it said so in that blog/video you’ve read/watched the other day); “Idiot — how do you not know about Arrow functions. Pshhaw!” gloats a colleague.

您说: “您不必使用function关键字声明函数吗?” (因为它说的是您前几天看过/看过的博客/视频); “ 白痴-您如何不知道Arrow功能。 sh!” 幸灾乐祸的同事。

Note: not my experience thankfully, but please reconsider your environment if it’s that hostile…
注意:值得庆幸的是,这不是我的经验,但是如果这很不利,请重新考虑您的环境…

So I give you this, a bluffer’s guide, to get you through your day. A highlight reel of JavaScript syntax introduced in ES2015+ that all the kids are using these days, as well as some not-so-well-known JS features. It will help disguise those awkward moments when you nod understanding and politely change subject.

因此,我给您提供这份指南,帮助您度过美好的一天。 ES2015 +中引入JavaScript语法的精华集,这几天所有孩子都在使用,以及一些不太知名的JS功能。 当您点头理解并礼貌地改变话题时,它将有助于掩盖那些尴尬的时刻。

Before you cry “Oh Greg you fool, you created an article that is TLDR, where am I going to find the 15+ minutes to read your article”. Firstly, I recognise that pain of not having enough time in life, so I empathise. Secondly, the article is broken into sections regarding a particular syntax, so if you’re not interested in Arrow functions, then skip it. Not sure about Template literals, then hang around for 2–3 mins, friend, and let me tell you all about it. You do not have to consume the article in its entirety in one go!

在您哭泣之前, “噢,您真傻,格雷格,您创建了一篇名为TLDR的文章,我将在这里找到15分钟以上的时间来阅读您的文章”。 首先,我认识到生活中没有足够时间的痛苦,所以我很同情。 其次,本文分为关于特定语法的部分,因此,如果您对Arrow函数不感兴趣,请跳过它。 不确定模板字面量,然后朋友闲逛2-3分钟,让我告诉您有关它的所有信息。 您不必一口气消费整个文章!

I make no attempt to hide that this article is for those learning JavaScript and have the basic knowledge of how JavaScript works! For this article to be of use to you, you must know how to write JavaScript (e.g. just the basics of functions, objects, etc.). If not, go check out my other JavaScript posts and/or supplement that with a video tutorial on JavaScript fundamentals if need be.

我不会试图掩盖这篇文章是针对那些学习JavaScript并具有JavaScript工作原理的基础知识的人! 为了使本文有用,您必须知道如何编写JavaScript(例如,仅是函数,对象等的基础知识)。 如果不是,请查看我的其他JavaScript帖子,和/或在需要时添加有关JavaScript基础的视频教程。

Also, this article explains mostly using syntax introduced in ES2015 and beyond which may not be supported in every browser. Using Babel, most syntax can be compiled for compatibility. For others like Set or includes(), you can polyfill, but that is beyond the scope of this article. Always check with browser compatibility tables, your projects browser support requirements, and your tech lead(s) about introducing something new

另外,本文主要介绍了ES2015中引入的语法,并且并非所有浏览器都支持 。 使用Babel,可以编译大多数语法以实现兼容性。 对于Setinclude()之类的其他对象 ,您可以进行polyfill,但这超出了本文的范围。 始终检查浏览器兼容性表 ,项目浏览器支持要求以及有关引入新功能的技术负责人

var是小家伙; 让和const是未来 (var is for chumps; let and const are the future)

let and const are new variable declarations introduced in ES2015. The difference between these and var are primarily variable scope.

letconst是ES2015中引入的新变量声明。 这些和var之间的区别主要是可变范围。

var is function scoped, which means its available in the function it’s declared and in nested functions. This means you get some crazy behaviour like:

var是函数范围的,这意味着它可以在声明的函数和嵌套函数中使用。 这意味着您会得到一些疯狂的行为,例如:

And I haven’t even talked (and won’t) about the confusion with hoisting.

而且我什至没有谈论(也不会)关于吊装的困惑

let and const are how variables should be declared. They are block scoped so your head doesn’t have to swivel owl-like on your neck in frustration over undesirable and mysterious variable values that persist beyond the ending brace. const has the added benefit of immutability so this guy should be your default unless mutability is specifically required.

letconst是应如何声明变量。 它们具有块作用域,因此您的头不必在脖子上像猫头鹰一样旋转,而不必为不需要的和神秘的变量值而烦恼,这些变量值一直持续到结束括号为止。 const具有不变性的额外好处,因此除非特别需要可变性,否则此人应该是您的默认设置。

One thing to be aware with const is that it only is immutable in its assignment. This is fine for primitive types like String or Number. Objects behave slightly differently; the object reference is immutable, but their properties are still mutable.

const要注意的一件事是,它仅在其分配中是不可变的。 这对于诸如String或Number之类的原始类型很好。 对象的行为略有不同。 对象引用是不可变的,但是它们的属性仍然可变。

Which should you use? Well, definitely not var. There are differing opinions on whether to use let or const. Ultimately it comes down to personal opinion or the project conventions. I subscribe to using const (contrary to my code examples) because of its immutability (object properties aside).

您应该使用哪个? 好吧,绝对不是var 。 关于是否使用letconst有不同的意见。 最终,它取决于个人意见或项目惯例。 我赞成使用const (与我的代码示例相反),因为它具有不变性(不包括对象属性)。

If you see var in code now, be the first to proclaim how you can improve the code quality by replacing with let and const and stop using it right now. Period.

如果您现在在代码中看到var ,请第一个声明如何通过用letconst替换并立即停止使用来提高代码质量。 期。

对象初始化的简写形式-节省您一些宝贵的时间 (Object initialisation short-hand notation — saving you some sweet precious time)

I am about to share with you information that will save you some seconds in precious time. Valuable time; Leaving you free to do things you love (or loath). An extra load of washing, another “Oh by the way” next time your chatty over the proverbial office watercooler, extra time to sit back and relax before your day’s scrum, etc.

我将与您分享一些可以节省您宝贵时间的信息。 宝贵的时间; 让您自由地做自己喜欢(或讨厌)的事情。 额外的洗衣服,下次当您对这个众所周知的办公室冷水机进行闲聊时,又一次“ ”,在一天的忙碌之前有更多的时间坐下来放松一下,等等。

Objects can be initialised with a form of shorthand notation that allows you to implicitly set both key-value pair on objects without having to state them explicitly, but by passing just the parameter variable.

可以用一种简写形式的形式初始化对象,该形式允许您隐式地在对象上设置两个键值对,而不必显式声明它们,而只需传递参数变量即可。

Note: MENSA haven’t emailed me; if they did, with that subject line, I’d be quite worried as I couldn’t be certain it would be positively good news…
注意:MENSA尚未通过电子邮件发送给我; 如果他们这样做的话,我会很担心,因为我无法确定这肯定是个好消息……

You must use this notation sensibly however, and not be the unfortunate engineer who tried to use keywords or duplicates in your function. The former will cause errors while the latter (and perhaps worse) will simply override your values with the latest argument value.

但是,您必须明智地使用此表示法,而不能成为试图在函数中使用关键字或重复项的不幸工程师。 前者将导致错误,而后者(可能更糟)将仅使用最新的参数值覆盖您的值。

模板文字-级联的酷猫 (Template literals — the cool cat of concatenation)

Template literals (AKA template strings) allow you to reference variables within strings, without all the fuss of explicit concatenation, using the backtick. Users of Slack and Medium will be instantly familiar with the ` symbol to denote code markup.

模板文字 (AKA 模板字符串 )允许您使用反引号来引用字符串中的变量,而不必大惊小怪地进行显式串联 Slack和Medium的用户将立即熟悉`符号来表示代码标记。

Take this standard example of concatenation:

采取以下标准串联示例:

Ugh, effort. You can make the code more effective using template literals:

gh,努力。 您可以使用模板文字使代码更有效:

We can even use it to replace the horrible newline escape character \n with no extra code sauce required.

我们甚至可以使用它来替换可怕的换行符\n ,而无需额外的代码。

We can also execute calculations and expression (fancily known as Expression interpolation) within a template literal without breaking our “string”:

我们还可以在不破坏我们的“字符串”的情况下,在模板文字内执行计算和表达式(俗称“ 表达式插值 ”):

And we can do some funky template literal nesting:

我们可以做一些时髦的模板文字嵌套

Template literals are the proverbial bee’s knees of JavaScript concatenation. In work projects, I’ve found it configured by default on linting rules so that explicit concatenation is auto-transformed to template literals. Don’t wait until a special holiday, impress your friends right now with your newfound concatenation syntax.

模板文字是JavaScript级联的蜜蜂。 在工作项目中,我发现默认情况下在棉绒规则上对其进行了配置,以便将显式级联自动转换为模板文字。 不要等到特殊的假期,立即用新发现的串联语法打动您的朋友。

默认参数-配备齐全 (Default Params — being fully equipped)

Like a lot of this new code syntax, I saw default params before I even knew they existed. Of course, reading the code I was perplexed and a little apoplectic over why a certain value that was being assigned a value wasn’t that value at runtime. It was 5 damnit — it says so right in the function param, how could it be a 10 at runtime! Damn code gremlins. Of course that momentary hissy fit was simply ignorance on my part.

像许多这种新的代码语法一样,我什至在不知道默认参数存在之前就已经看到它们。 当然,阅读代码让我感到困惑,并且对为什么分配了某个值的某个值在运行时不是那个值感到困惑。 这真是太过分了5 —在函数参数中说得很对,在运行时怎么可能是10! 该死的代码gremlins。 当然,短暂的嘶嘶声完全是我的无知。

Default params allow you to use, you guessed it folks, a parameter…by DEFAULT! As much I am lampooning it, it is actually a simple (like a slap to the forehead to cajole the brain to wake-up simple) but effective means of controlling the unpredictability of the undefined entering your function contract.

默认参数允许您使用,您猜到了,一个参数…… 由DEFAULT! 就我而言,它实际上是一个简单的过程(就像额头上的耳光叫动大脑唤醒一样简单),但是却是控制undefined进入您的功能合同的不可预测性的有效手段。

For example, most software developers across the spectrum of languages have at some stage seen if(something != null) (looking at you Java) around code blocks simply because there is always that 1% chance our enemy will pass an object or value that is not something we expect, and we must take it as an absolute certainty they will.

例如,跨语言的大多数软件开发人员在某个阶段都在代码块周围看到了if(something != null) (看着您的Java) ,仅仅是因为我们的敌人总是有1%的机会通过一个对象或值这不是我们期望的事情,我们必须将其作为绝对确定的理由。

Imagine if your bank account had a function that one day got passed an undefined. I imagine that surgery would be required to re-attach the jaw after it dropped from your face if you saw your account balance as NaN.

想象一下,如果您的银行帐户具有某项功能,有一天可以通过undefined 。 我想如果您的帐户余额显示为NaN ,那么从您的下巴掉下来后,就需要重新手术以重新固定下颌。

So how to defend? Correct — default params.

那么如何捍卫呢? 正确-默认参数。

Simple yet effective.

简单而有效。

Now this is a contrived example and many will point out the myriad ways to stop the economic collapse of the world accounting systems from NaN in different ways. Hold off my friend — it was just to show this example.

现在,这是一个人为的例子,许多人将指出以各种方式阻止NaN阻止世界会计系统的经济崩溃的多种方法。 放开我的朋友-只是为了展示这个例子。

Default params guard against the undefined so you are correct when you think “what if a non-expected type of value is entered — Default params won’t guard against that”. Indeed so true and depending on your code, you may need additional checks to ensure the type of value of correct.

默认参数防止undefined因此当您认为“ 如果输入了非预期类型的​​值怎么办—默认参数将不会防止 undefined ,您是正确的。 确实如此,根据您的代码,您可能需要进行其他检查以确保值的正确类型。

解构—价值分配向导 (Destructuring — Value assignment wizardry)

When I first saw objects being destructured (not knowing what the flip I was looking at), I was mightily confused. Curly braces I associated with object notation, but in the variable name declaration with a bunch of other names all pointing to the one object reference? Dark wizardry indeed.

当我第一次看到物体被破坏(不知道我在看什么翻转)时,我非常困惑。 花括号我与对象表示法相关联,但是在变量名声明中有一堆其他名称都指向一个对象引用吗? 确实是黑暗巫师。

The reality is that it’s quite simple but it’s use will make you look so wizard, even Harry will be jealous. The concept is this: you declare immediate variables with values that match the same-named properties on an object.

现实情况是,它很简单,但是它的使用会使您看起来很巫师,甚至哈利也会嫉妒。 概念是这样的:您声明立即变量,其值与对象上的同名属性匹配。

No more someObject.someProperty; just simple variables to for our further programming needs.

不再需要someObject.someProperty; 只是简单的变量,以满足我们进一步的编程需求。

What happens if the variable isn’t available or we simply don’t want all the variables? Well we can create variables only for the values we want, and if we declare a variable that isn’t on the object, we simply get the same value as if we normally declared a variable without defining: undefined

如果变量不可用或者我们只是不希望所有变量,会发生什么? 好吧,我们只能为所需的值创建变量,如果我们声明一个不在对象上的变量,我们将获得与通常声明时undefined的变量相同的值: undefined

But the magic doesn’t stop there. We can ensure that our variables have defaulted values in case they aren’t assigned.

但是魔术并不止于此。 如果未分配变量,我们可以确保变量具有默认值。

And if we want, we can even rename the variables as we want them. Sorcery indeed.

如果需要,我们甚至可以根据需要重命名变量。 法术的确如此。

And as long as it’s an object that your destructuring, it doesn’t matter whether it’s destructured directly, or given as a return object on a function.

并且只要它是您要进行销毁的对象,无论它是直接销毁还是作为函数上的返回对象提供,都没有关系。

That also includes destructuring at the parameter level. Why would you do that, you ask? It removes the need to have parameter order when invoking a function. I do not lie.

这还包括在参数级别进行销毁。 你问为什么要这么做? 调用功能时,无需具有参数顺序 。 我不说谎。

Just like objects, we can do all this with Arrays. The trick is to use the Array braces notation rather than object braces. Assignment is given by index order of the array, so the first variable is assigned the first index item, and so on.

就像对象一样,我们可以使用数组来完成所有这些工作。 诀窍是使用数组大括号符号而不是对象大括号。 分配由数组的索引顺序指定,因此第一个变量被分配第一个索引项,依此类推。

The above examples of destructuring are a good summary of what you can do, but if you really want to become the Gandalf of JavaScript destructuring, then check out the MDN destructuring assignment documentation.

上面的销毁示例很好地概括了您可以做的事情,但是如果您真的想成为JavaScript销毁的甘道夫,请查看MDN销毁分配文档

For..of循环—迭代迭代 (For..of loop — iterating iterants iteratively)

The for..of loop in JavaScript allows more effective looping of iterables. Often people think of iterables as Arrays (and they’re right of course), but iterables can also be the characters in a String, the key-value pairs in a Map, elements of a Set, etc. (pssshhh — see more Iterable types here).

JavaScript中的for..of循环可实现更有效的可迭代循环。 人们通常将可迭代对象视为数组(当然是对的),但是可迭代对象也可以是字符串中的字符,映射中的键值对,集合的元素等。(pssshhh,请参阅更多在此处输入 )。

You may be thinking, aren’t there other for loops in JavaScript, and you’d be right — there are; the traditional for, the for..in, the while and the do..while, the forEach and map. So what’s special with for..of?

您可能在想, JavaScript中是否还没有其他for循环 ,您将是对的-那里有; forfor..inwhiledo..whileforEachmap 。 那么for..of什么特别的呢?

The best way I describe to myself the difference between for..of and for..in is that, while both iterate over lists, for..in returns keys on the object, where for..of returns values of the object being iterated.

我对自己描述for..offor..in之间的区别的最好方法是,虽然两者都遍历列表,但是for..in返回对象上的键,而for..of返回要迭代的对象的值。

The difference is more apparent in Strings.

区别在字符串中更明显。

So why bother with the other for loops well-armed with the artillery of for..of? Well, the for..of doesn’t allow mutation (i.e. change) of the array like for would. It also it doesn’t work well on the properties of objects like for..in.

那么,为什么还要为for..of火炮装备精良的for循环而for..of呢? 好吧, for..of不允许像for那样对数组进行突变(即change )。 它也无法在for..in之类的对象的属性上正常工作。

I found the different ways of looping in JavaScript fine, including for..of but most of my uses were satisfied by using map, filter, and reduce which are iterant royalty and that I describe further down.

我发现JavaScript可以很好地循环使用不同的方式,包括for..of但是我的大多数使用都通过使用mapfilterreduce来满足,这是迭代的使用费,我将在以后进行介绍。

Likely, for..of will be the least useful for you on this list but will still impress others with your knowledge at least.

在此列表中, for..of可能对您的用处最少 ,但至少仍会以您的知识打动其他人。

数组包括—我没有索引 (Array includes — No indexing for me)

In a work project, I saw indexOf being used to check a value within an array. It also had the check for -1 to be sure that there was logic to handle if it wasn’t found — if(array.indexOf(b) < 0) {..}. In one of my rare flashes of inspiration, I had the thought that since I had seen all this new syntax I’m describing in this article, that surely some clever-clogs had made this easier and more readable! Surely. And I was right.

在一个工作项目中,我看到indexOf用于检查数组中的值。 它还对-1进行了检查,以确保是否存在可以处理的逻辑if(array.indexOf(b) < 0) { ..}。 在我难得的灵感中,有一种想法是,既然我已经看到了我在本文中描述的所有新语法,那么肯定会有一些巧妙的堵塞使它变得更容易和更易读! 一定。 我是对的。

Array.prototype.includes() allows you to, more readably and more logically, check if certain arrays have certain values. It returns a simple boolean rather than some sentinel number value and overall, should be the defacto for array interrogation.

Array.prototype.includes()使您可以更方便,更逻辑地检查某些数组是否具有某些值。 它返回一个简单的布尔值,而不是一些标记值,总的来说,它应该是数组查询的事实。

One caveat — that work project I was on needed to support IE11 as a browser. And guess what? For the browser-that-will-not-die, it’s not supported. There is a polyfill available for those that have to work under such dramatic conditions.

一个警告—我需要从事的那个工作项目才能将IE11作为浏览器来支持。 你猜怎么着? 对于不会死的浏览器,不支持。 对于那些需要在如此剧烈的条件下工作的人,可以使用一种填充料。

套装—工作场所的多样性 (Set — Diversity in the workplace)

For when you don’t want your array to have duplicate values, a Set is your friend. If you know Java and know all about the Set interface and implementations, this isn’t really new, so here’s a pass and skip on through.

对于当您不希望数组具有重复值时,Set是您的朋友。 如果您了解Java并且了解Set 接口和实现的全部知识,那么这并不是真正的新事物,因此这里是一个传递和跳过的过程。

A set is an object that takes an array and is able to strip it of duplicate values.

集合是一个对象,它采用数组并能够剥离重复值。

The Set has a bunch of functions such as add, delete, forEach, etc. that allow you to traverse and manipulate the set in question.

该集合具有一堆功能,例如adddeleteforEach等,使您可以遍历和操纵相关集合。

传播-传播对价值的热爱 (Spread — spreading the love of values)

The Spread operator, while I personally think its name is confusing for its use, is actually one of the most helpful new syntax additions.

虽然我个人认为Spread运算符的名称让人困惑,但实际上它是最有用的新语法添加之一。

The Spread operator syntax is three fullstops (…) before the object reference.

Spread运算符语法在对象引用之前为三个句号(...)。

The Spread operator essentially expands an iterable object containing values and places them into a space where multiple values are expected (by value and not by reference). Still confused? That’s fine — let’s break this down further.

Spread运算符本质上扩展了一个包含值的可迭代对象,并将它们放置在期望多个值(按值而不是按引用)的空间中。 还是很困惑? 很好-让我们进一步细分一下。

Let’s combine some arrays into larger arrays.

让我们将一些数组组合成更大的数组。

Our use of the spread passes these objects by value and not by reference. It means that we can mutate the original array without worry that a composed array is changed.

我们使用点差通过而不是通过引用传递这些对象。 这意味着我们可以更改原始数组,而不必担心更改了​​组成的数组。

So sure, seems obvious now, you can essentially compose arrays like Lego blocks of other arrays. That’s fine, but what else?

所以可以肯定,现在看来很明显,您可以像其他数组的Lego块一样组成数组。 很好,但是还有什么呢?

Well Spreads can be used in function argument lists.

良好的价差可以在函数参数列表中使用。

It follows the typical rues of JavaScript function arguments whereby additional values are not used and lacking arguments are undefined.

它遵循由此,不使用附加的值,并缺乏自变量JavaScript函数参数的典型rues undefined

So arrays, check. Function arguments, check. Spread sounds great, doesn’t it? Well it has one last lovely surprise it really wants to show you — by spreading object literals!

因此,检查数组。 函数参数,检查。 传播听起来不错,不是吗? 好吧,它确实想向您展示最后一个可爱的惊喜-通过传播对象文字!

In this way, we can compose our objects with smaller objects. Non-unique key properties are overwritten by the latest value while unique properties are added.

这样,我们可以用较小的对象组成对象。 添加唯一属性时,非唯一键属性将被最新值覆盖。

One caveat; the spread of object literals is more cutting edge (at time of writing) than the other syntax features here (being introduced in ES2018).

一个警告: 与本文中的其他语法功能(在ES2018中引入)相比,对象文字的传播(在撰写本文时)更具前沿性。

For more information on Spread and the general browser support for that spreading, see the MDN article on Spread syntax (especially the browser compatibility table).

有关Spread和该扩展的常规浏览器支持的更多信息,请参见有关Spread语法MDN文章 (尤其是浏览器兼容性表)。

休息员—接受您的所有其他人 (Rest operator — Accepting of all the rest of you)

If you understand the Spread syntax, this should seem like a natural extension of its functionality. If you happen to come from a Java background, I’ll simply say varargs so that you can move quickly on.

如果您了解Spread语法,这似乎是其功能的自然扩展。 如果您碰巧是来自Java背景,我会简单地说varargs,以便您可以快速进行。

The Rest operator is syntax that allows a reference to as many arguments as are passed into a function. It allows functions to accept as many arguments as you want to throw at them (as long as the Rest operator is the only and last function argument). I think of its name as a reference to all the rest of the arguments a function should use.

Rest运算符是一种语法,它允许引用与传递到函数中一样多的参数。 它允许函数接受任意数量的参数(只要Rest运算符是唯一且最后一个函数参数)。 我认为它的名称是对函数应使用的所有其他参数的引用。

That’s it. Simples.

而已。 简单。

Wait, what about arguments? Why not use that? Well, arguments is a funny thing, because it doesn’t return an array, but rather an array-like object. Because of this, we can’t treat it like an array.

等等, arguments呢? 为什么不使用它? 好吧, arguments是一件很有趣的事情,因为它不返回数组,而是返回类似数组的对象。 因此,我们不能将其视为数组。

In most cases, you don’t want your functions accepting of as many arguments as some hooligan engineers will want to chuck at it. It can lead to unpredictability; let’s be honest, the job is hard enough without adding more complexity to it. There will be use cases where of course you need to be open to everything (e.g. a sum function) and when these happen, the Rest operator is what you need.

在大多数情况下,您不希望您的函数接受像一些流氓工程师所希望的那样多的参数。 它可能导致不可预测性; 说实话,这份工作是没有增加更多的复杂性,它够硬。 在某些用例中,您当然需要对所有内容都开放(例如求和函数),并且在发生这些情况时,需要使用Rest运算符。

箭头功能-直接指向功能点 (Arrow functions — straight to the functional point)

More and more code I see nowadays use Arrow functions rather than the traditional function syntax. Personally, my background came from Java which is typically known for it’s verbosity, so I fall into that style quite naturally. Knowing arrow functions will go a long way to bluffing JavaScript proficiency among your peers, winning you friends, and influencing people.

如今,我看到越来越多的代码使用Arrow函数而不是传统的function语法。 就我个人而言,我的背景来自Java(通常以冗长而著称),因此我很自然地陷入了这种风格。 知道箭头功能将大大提高同行之间JavaScript熟练程度,赢得您的朋友并影响人们。

Arrow functions streamline the traditional function syntax to be less verbose and shorter to implement. Of course there is minor differences between it and function expressions (such as no this, super, or arguments), but generally that’s an acceptable trade-off.

箭头函数简化了传统函数的语法,使其冗长且易于实现。 当然,它与函数表达式之间没有细微的差别(例如no thissuperarguments ),但是通常这是一个可以接受的折衷方案。

In one-liners like above, not only did we get rid of the function keyword, we were also able to be rid of the curly braces and the return keyword. This is known as the ‘concise body’. You can of course still use curly braces for multi-line logic which is known as ‘block body’.

在像上面这样的单行代码中,我们不仅摆脱了function关键字,而且还摆脱了花括号和return关键字。 这就是所谓的“ 简洁的身体 ”。 当然,您仍然可以将花括号用于多行逻辑,这被称为“ 块体 ”。

Arrow functions are effectively suited to be used in callbacks.

箭头函数有效地适合在回调中使用。

Yes, yes, I know, the code above could have been streamlined, like the scales of an elegant fish, to be a one-liner; but if I did that, I couldn’t show a multi-line Arrow function!
是的,是的,我知道,上面的代码可以简化,就像一条优雅的鱼鳞一样,成为一条线。 但是,如果这样做,我将无法显示多行箭头功能!

Arrow functions have become more prevalent in JavaScript frameworks such as React, where seeing stateless components defined using arrow functions is quite ordinary.

箭头函数在诸如ReactJavaScript框架中变得越来越普遍,在其中看到使用箭头函数定义的无状态组件非常普遍。

This is really only a snippet of what Arrow functions can do, but as a bluffer’s guide, it’s enough to see you through the day without attracting the scrutiny of the your autocratic colleagues.

这实际上只是Arrow函数可以执行的功能的一小段,但作为骗子的指南,足以一整天地看到您,而不会引起专制同事的审查。

So get out there and start firing arrows everywhere; Point arrows at all your friend’s functions; it will enamor everyone of your JavaScript proficiency all the more. Become as accurate as an archer, and for masterclass lessons — see the MDN documentation on Arrow functions.

所以走到那里,开始向各处发射箭; 将箭头指向您朋友的所有功能; 它将更加吸引您JavaScript熟练度。 变得像弓箭手一样精确,并掌握大师级课程—请参阅有关Arrow函数MDN文档。

计算的属性名称-不计算吗? (Computed property names — does not compute?)

Computed property names are the names of properties that are derived from the values of other variables. Unfortunately, you cannot assign variables directly as a key to an object.

计算属性名称是从其他变量的值派生的属性的名称。 不幸的是,您不能直接将变量作为键分配给对象。

One tool available is to use the square bracket notation. This can be used to access properties on an object, just like it’s foe, the dot operator. For example, person['name'] is the same as person.name.

一种可用的工具是使用方括号表示法。 可以使用它来访问对象的属性,就像它的敌人运算符一样。 例如, person['name']person.name相同。

We can also use the same syntax to set properties on objects using their value as the key.

我们还可以使用相同的语法,以对象的值作为键来设置对象的属性。

What’s even better is that since ES2015, this has gotten a helluva lot easier! No more messing with creating the object, then assigning the value afterward, and other stuff, ugh so messy. Just straight up key-value setting. What a relief.

更好的是,自ES2015以来,这变得更容易了! 再也不必创建对象,然后再分配值了,其他事情也变得如此混乱。 只需直接进行键值设置即可。 终于解脱了。

映射,过滤,缩小—不是制图 (Map, filter, reduce — Not cartography)

I came late to the game learning map, filter, and reduce, and worse still these aren’t new or modern syntax.

我来游戏学习mapfilterreduce很晚,更糟糕的是,这些并不是新的现代的语法。

I used typical looping syntax (e.g. for) coming from a Java background. That means when I had to look through elements within the array, I often created a new empty array, interrogated the valued array, and transfer the elements I wanted.

我使用的典型循环语法(如for )从Java背景的。 这意味着当我不得不浏览数组中的元素时,我经常创建一个新的空数组,询问有价数组,然后传输我想要的元素。

Such wasted effort. Thankfully there are nicer ways to complete these ordeals.

这种浪费的精力。 幸运的是,还有更好的方法可以完成这些考验。

I like to think of using map for when my needs are:

我想在需要时使用map

  • I need to transform the contents of an array

    我需要转换数组的内容

  • I return a new array

    我返回一个新数组

So what do I mean by transform? Well that’s a good question, it could be to manipulate the array contents in any means. For example if I want to double the numbers in a number array, or (more practically) create a bunch of HTML elements with values from a String array.

那么, 变换是什么意思? 嗯,这是一个很好的问题,它可以以任何方式操纵数组的内容。 例如,如果我想将数字数组中的数字加倍,或者(更实际地)使用String数组中的值创建一堆HTML元素。

Generally, map is suitable for most looping needs I’ve found and it also retains the immutability of the original array by returning a new array, which is great. It has become my default way of looping in most use cases.

通常, map适合我发现的大多数循环需求,并且通过返回一个新数组,它还保留了原始数组的不变性,这很棒。 在大多数情况下,它已成为我默认的循环方式。

filter is, as the name suggests, filters an array and returns a new copy of that array (filtered of course). Very similar in most respects to map, the only difference is the callback must return a boolean value (to indicate whether the value should be retained or not). Magical!

顾名思义, filter是过滤一个数组并返回该数组的新副本 (当然是过滤的)。 在大多数方面与map非常相似,唯一的区别是回调必须返回布尔值(以指示是否应保留该值)。 神奇!

Finally, reduce is the act of reducing your array to a single value, (how deductive of you). Anecdotally, I haven’t seen much use of this outside numbers other than concatenation of Strings, etc. But hey, if it’s the right tool for the right job, then who am I to argue.

最后, reduce是将数组缩减为单个值(对您的推论能力)的行为。 有趣的是,除了串等之外,我还没有看到过多使用此外部数字。但是,嘿,如果这是完成正确工作的正确工具,那么我该争论谁呢。

reduce is a little different from map and reduce in so far that it takes an accumulator or previous value (representing the total so far) and the current value.

reducemap有所不同, reduce到目前为止,它需要一个累加器先前值(代表到目前为止的总和)和当前值

That’s cool — I can take a bunch of numbers and reduce to a single value based on a rule. From there I could get averages, counts, deviations, and apply a whole agglomeration of mathematical magic trickery.

太酷了–我可以接受一堆数字,然后根据规则将其简化为单个值。 从那里我可以得到平均值,计数,偏差,并应用整个数学魔术技巧的集聚。

But what about objects? Well you can…sort of. Reduce can take an initial object, append properties and attach values. As said before, I haven’t personally seen many use cases other than counting the number of times an object is in an array, and then assigning the count values to a return object. So with that bombshell….

但是对象呢? 好吧,你可以...有点。 Reduce可以采用初始对象,附加属性并附加值。 如前所述,除了计算对象在数组中的次数,然后将计数值分配给返回对象之外,我还没有看到许多用例。 因此,有了重磅炸弹……。

What’s great about map, filter, and reduce, is that they are functions of the Array, and as they all return arrays, it means they can be chained together, one after the other. Powerful stuff indeed.

mapfilterreduce 的优点在于它们是Array的函数 ,并且它们都返回数组时,意味着它们可以一个接一个地链接在一起。 确实功能强大。

上课-如何保持上等 (Classes — how to stay classy)

For those who’ve read my other article OOP Digest in JavaScript, or those who have experienced the joys of React (yes I said it), classes aren’t unfamiliar. However what was the surprise to me, hopping into React before understanding modern JS, was the the class syntax was a product of vanilla JavaScript and not a library or framework.

对于那些已经阅读过我的其他文章《用JavaScript编写OOP Digest》的人 ,或者那些已经体验过React的乐趣(是的,我说过)的人来说,类并不陌生。 但是,令我惊讶的是,在理解现代JS之前跳入React的是, class语法是普通JavaScript的产物,而不是库或框架。

Classes is nearly another article to write and to be fair, this already is quite a cumbersome article, so to be concise I will highlight the simplified understanding and set you packing with the map to find more informational treasure.

Classes几乎是另一篇要撰写的文章,并且公平地说,这已经是一件繁琐的文章,因此,为了简洁起见,我将突出显示简化的理解,并为您提供丰富的地图资料,以找到更多的信息宝藏。

So before you worry about how complicated Classes are, there is a simple comfort to know: JavaScript’s object-orientated prototypal model hasn’t changed. Sky is up and ground is down for those of us who are still somewhat upright. MDN defines classes as syntactical sugar over JavaScript’s existing prototype-based inheritance and a lovely way to say — it’s just another way to create objects (hint: ‘object-orientated’).

因此,在担心类的复杂性之前,有一个简单的需要知道的地方:JavaScript的面向对象的原型模型没有改变。 对于仍然有些直立的我们这些人来说,天空是高空的,地面是低空的。 MDN将类定义为JavaScript现有的基于原型的继承的 语法糖 还有一种可爱的说法-这是创建对象的另一种方法(提示:“面向对象”)。

Traditionally, we used function to create objects in JavaScript, and we still can of course. But classes safely replace the idea of using a function Dog() {} to create objects by removing the confusion around functions who are, well, functions, and those used in constructor mode.

传统上,我们使用function在JavaScript中创建对象,我们当然可以。 但是,类消除了围绕函数(这些函数以及构造函数模式下使用的function Dog() {}的混淆,从而安全地替换了使用function Dog() {}创建对象的想法。

It does this by forcing the use of the new keyword. Previously, when a function that was actually a constructor function (i.e. needed new) was called the old fashioned way, the properties were actually set on the callee object, which of course caused pandemonium to ensue.

它通过强制使用new关键字来实现。 以前,当实际上是构造函数(即,需要new )的函数称为旧方法时,实际上是在被调用者对象上设置了属性,这当然导致了pandemonium的出现。

There are a bunch more features of classes to consider:

还有很多需要考虑的类功能:

  • Constructors

    建设者

Constructors can be used for object initialisation and come with their OWN reserved keyword.

构造函数可用于对象初始化,并带有OWN保留关键字。

  • Object functions

    对象功能

Previously, if we wanted an object “type” to contain a function accessible to all of that type, we would set it on that object’s prototype. Laborious. Now we can easily just add it to the class.

以前,如果我们希望对象“类型”包含可用于所有该类型的函数,则可以在该对象的原型上进行设置。 费力的。 现在,我们可以轻松地将其添加到类中。

  • Getters/Setters

    获得者/设定者

Classes can use get and set keywords as accessors/mutators to access variables on a class. As a rule, classes cannot contain instance variables declared at class level (like Java), but can contain standard object properties defined and retrieved using functions. Note: our _ convention to denote something private isn’t actually private in JavaScript and is accessible.

类可以使用getset关键字作为访问器/更改器来访问类上的变量。 通常,类不能包含在类级别声明的实例变量( 如Java ),但是可以包含使用函数定义和检索的标准对象属性。 注意:我们的_约定表示私有的内容实际上不是JavaScript私有的,可以访问。

  • Inheritance

    遗产

Inheritance is quite similar to anyone with a background in OOP languages like Java. It, at its most simplistic, allows you to pass down functions from a parent type to a child type. This was apparently quite tedious to do prior to ES2015.

继承与具有Java等OOP语言背景的任何人都非常相似。 它以最简单的方式允许您将函数从父类型传递到子类型。 在ES2015之前,这样做显然很繁琐。

To pack you on the way for more information — I would thoroughly recommend an article in JavaScript ES6 Class Syntax by Cory Rylan which I found most enlightening to the world of JavaScript classes. It’s quick and full of nice(r) code examples comparing old and new JavaScript syntax.

为了给您提供更多信息,我将彻底推荐Cory Rylan撰写的JavaScript ES6 Class Syntax中的一篇文章,该文章对JavaScript类的世界很有启发。 它快速且充满了不错的代码示例,比较了新旧JavaScript语法。

摘要 (Summary)

So armed (secretly of course) with this bluffer’s guide, you should be the envy of your friends, feared by your enemies, and be well on your way to leveling-up with all your newfound JavaScript experience points.

因此,(当然是秘密地)掌握了该Blur的指南,您应该羡慕您的朋友,并为您的敌人所恐惧,并在逐步提升所有新发现JavaScript经验点的过程中保持良好状态。

This article was long yes, I make no apology for my bardic articulation. However, you might offer a different and more violent counter-argument; so if I was to offer a minimal set of take-aways — focus on let/const, Arrow functions, Spread and Destructuring.

长期以来,这篇文章是肯定的,我不为自己的裸露道歉道歉。 但是,您可能会提供另一种更激烈的反驳。 因此,如果我要提供最少的外卖服务-专注于let / const,Arrow函数,SpreadDestructuring。

Lastly, I hope you think of me when you’re rich and famous from the teaching of this article. Take comfort in knowing that I will be angrily shaking my fist.

最后,我希望您能从本文的教学中获得富裕和成名时想到我。 知道我会愤怒地摇拳时,请放心。

If you’ve read this article, simply skipped it after a paragraph or two, or more simply you don’t really give a flying fudge; please feed my public validation addiction anyway by giving me a clap, and then go checkout my other articles.
如果您已阅读本文,只需在一两段之后就跳过它,或者更简单地说,您实际上并没有做出任何轻率的准备; 无论如何,请给我鼓掌以养活我的公共验证癖,然后查看其他文章。
If you didn’t like this article and would like to register your resentment, you can do so by giving a hateful clap.
如果您不喜欢本文,但想表达您的不满,可以通过令人讨厌的鼓掌来实现。

The opinions expressed in this publication are those of the author. They do not purport to reflect the opinions or views of any organisation or business that the author may be connected to.

本出版物中表达观点为作者的观点 。 它们并非旨在反映作者可能与之联系的任何组织或企业的观点或看法。

翻译自: https://www.freecodecamp.org/news/bluffers-guide-to-javascript-proficiency-18195dbe2618/

javascript指南

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值