博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
查看这些有用的ECMAScript 2015(ES6)提示和技巧
阅读量:2522 次
发布时间:2019-05-11

本文共 9233 字,大约阅读时间需要 30 分钟。

by rajaraodv

通过rajaraodv

查看这些有用的ECMAScript 2015(ES6)提示和技巧 (Check out these useful ECMAScript 2015 (ES6) tips and tricks)

EcmaScript 2015 (aka ES6) has been around for couple of years now, and various new features can be used in clever ways. I wanted to list and discuss some of them, since I think you’ll find them useful.

EcmaScript 2015(又名ES6)已经存在了两年,并且可以巧妙地使用各种新功能。 我想列出并讨论其中的一些,因为我认为您会发现它们很有用。

If you know of other tips, please let me know in the comment and I’ll be happy to add them.

如果您知道其他提示,请在评论中让我知道,我们很乐意添加它们。

1.强制执行必需的参数 (1. Enforcing required parameters)

ES6 provides that allow you to set some default value to be used if the function is called without that parameter.

ES6提供了 ,如果不使用该参数调用该函数,则可以设置一些默认值。

In the following example, we are setting the required() function as the default value for both a and b parameters. This means that if either a or b is not passed, the required() function is called and you’ll get an error.

在下面的示例中,我们将required()函数设置为ab参数的默认值。 这意味着,如果未传递ab ,则会调用required()函数,并且会出现错误。

const required = () => {throw new Error('Missing parameter')};
//The below function will trow an error if either "a" or "b" is missing.const add = (a = required(), b = required()) => a + b;
add(1, 2) //3add(1) // Error: Missing parameter.

2.强大的“减少” (2. The mighty “reduce”)

Array’s r method is extremely versatile. It is typically used to convert an array of items into a single value. But you can do a lot more with it.

Array的方法非常通用。 它通常用于将项目数组转换为单个值。 但是您可以做更多的事情。

?Tip: Most of these tricks rely on the initial value being an Array or an Object instead of a simple value like a string or a variable.

提示:大多数技巧都依赖于数组或对象的初始值,而不是字符串或变量之类的简单值。

2.1 Using reduce to do both map and filter *simultaneously*

2.1使用reduce同时进行映射和过滤

Suppose you have a situation where you have a list of items, and you want to update each item (that is, ) and then filter only a few items (that is, ). But this means that you would need to run through the list twice!

假设你有,你有项目清单的情况,以及要更新的每个项目(即 ),然后过滤只有少数项目(即 )。 但这意味着您将需要两次浏览列表!

In the below example, we want to double the value of items in the array and then pick only those that are greater than 50. Notice how we can use the powerful reduce method to both double (map) and then filter? That’s pretty efficient.

在下面的示例中,我们希望将数组中的项的值加倍,然后仅选择大于50的项。请注意,我们如何使用功能强大的reduce方法来对(映射)进行加倍(然后过滤)? 那是非常有效的。

const numbers = [10, 20, 30, 40];
const doubledOver50 = numbers.reduce((finalList, num) => {    num = num * 2; //double each number (i.e. map)    //filter number > 50  if (num > 50) {    finalList.push(num);  }  return finalList;}, []);
doubledOver50; // [60, 80]

2.2使用“缩小”代替“映射”或“过滤器” (2.2 Using “reduce” instead of “map” or “filter”)

If you look at the above example (from 2.1) carefully, you’ll know that reduce can be used to filter or map over items! ?

如果仔细查看上面的示例(从2.1开始),您会知道reduce可以用于过滤或映射项目!

2.3使用reduce来平衡括号 (2.3 Using reduce to balance parentheses)

Here’s another example of how versatile the reduce function is. Given a string with parentheses, we want to know if they are balanced, that is that there’s an equal number of “(“ and “)”, and if “(“ is before “)”.

这是reduce函数用途广泛的另一个示例。 给定带括号的字符串,我们想知道它们是否平衡,即是否有相等数量的“(”和“)”,以及“(”在“)之前”。

We can easily do that in reduce as shown below. We simply hold a variable counter with starting value 0. We count up if we hit ( and count down if we hit ) . If they are balanced, then we should end up with 0.

我们可以轻松地通过减少操作做到这一点,如下所示。 我们只是持有一个起始值为0的变量counter 。如果命中,我们就递增计数(如果命中) ,就递减计数。 如果它们是平衡的,那么我们应该以0结尾。

//Returns 0 if balanced.const isParensBalanced = (str) => {  return str.split('').reduce((counter, char) => {    if(counter < 0) { //matched ")" before "("      return counter;    } else if(char === '(') {      return ++counter;    } else if(char === ')') {      return --counter;    }  else { //matched some other char      return counter;    }      }, 0); //<-- starting value of the counter}
isParensBalanced('(())') // 0 <-- balancedisParensBalanced('(asdfds)') //0 <-- balanced
isParensBalanced('(()') // 1 <-- not balancedisParensBalanced(')(') // -1 <-- not balanced

2.4计算重复的数组项(转换数组→对象) (2.4 Counting Duplicate Array Items (Converting Array → Object))

There are times when you want to count duplicate array items or convert an array into an object. You can use reduce for that.

有时您想计算重复的数组项或将数组转换为对象。 您可以为此使用reduce。

In the below example, we want to count how many cars of each type exist and put this figure into an object.

在下面的示例中,我们要计算每种类型有多少辆汽车,并将该数字放入对象中。

var cars = ['BMW','Benz', 'Benz', 'Tesla', 'BMW', 'Toyota'];
var carsObj = cars.reduce(function (obj, name) {    obj[name] = obj[name] ? ++obj[name] : 1;  return obj;}, {});
carsObj; // => { BMW: 2, Benz: 2, Tesla: 1, Toyota: 1 }

There are plenty more things you can do using reduce, and I encourage you to read the examples listed on MDN .

使用reduce可以做更多的事情,我鼓励您阅读MDN 列出的示例。

3.对象分解 (3. Object destructuring)

3.1删除不需要的属性 (3.1 Removing unwanted properties)

There are times when you want to remove unwanted properties — maybe because they contain sensitive info or are just too big. Instead of iterating over the whole object to removing them, we can simply extract such props to variables and keep the useful ones in the *rest* parameter.

有时候,您想要删除不需要的属性-可能是因为它们包含敏感信息或太大。 无需遍历整个对象以删除它们,我们可以简单地将此类道具提取到变量中并将有用的道具保留在* rest *参数中。

In the below example, we want to remove _internal and tooBig properties. We can assign them to_internal and tooBig variables and store the remaining in a *rest* parameter cleanObject that we can use for later.

在下面的示例中,我们要删除_internaltooBig属性。 我们可以将它们分配给_internaltooBig变量,并将剩余的变量存储在* rest *参数 cleanObject ,以备后用。

let {_internal, tooBig, ...cleanObject} = {el1: '1', _internal:"secret", tooBig:{}, el2: '2', el3: '3'};
console.log(cleanObject); // {el1: '1', el2: '2', el3: '3'}

3.2分解函数参数中的嵌套对象 (3.2 Destructure nested objects in function params)

In the below example, the engine property is a nested-object of the car object. If we are interested in, say, the vin property of engine, we can easily destructure it as shown below.

在下面的示例中, engine属性是car对象的嵌套对象。 例如,如果我们对enginevin属性感兴趣,我们可以轻松地对其进行分解,如下所示。

var car = {  model: 'bmw 2018',  engine: {    v6: true,    turbo: true,    vin: 12345  }}
const modelAndVIN = ({model, engine: {vin}}) => {  console.log(`model: ${model} vin: ${vin}`);}
modelAndVIN(car); // => model: bmw 2018  vin: 12345

3.3合并对象 (3.3 Merge objects)

ES6 comes with a spread operator (denoted by three dots). It is typically used to deconstruct array values, but you can use it on Objects as well.

ES6带有一个扩展运算符(由三个点表示)。 它通常用于解构数组值,但是您也可以在对象上使用它。

In the following example, we use the spread operator to spread within a new object. Property keys in the 2nd object will override property keys in the 1st object.

在下面的示例中,我们使用传播算子在新对象中传播。 第二个对象中的属性键将覆盖第一个对象中的属性键。

In the below example, property keys b and c from object2override those from object1

在下面的示例中, object2属性键b and c覆盖了object1属性键

let object1 = { a:1, b:2,c:3 }let object2 = { b:30, c:40, d:50}let merged = {…object1, …object2} //spread and re-add into mergedconsole.log(merged) // {a:1, b:30, c:40, d:50}

4.套装 (4. Sets)

4.1使用集对数组进行重复数据删除 (4.1 De-duping Arrays Using Sets)

In ES6 you can easily de-dupe items using Sets, as Sets only allows unique values to be stored.

在ES6中,您可以使用Set轻松删除重复项,因为Set仅允许存储唯一值。

let arr = [1, 1, 2, 2, 3, 3];let deduped = [...new Set(arr)] // [1, 2, 3]

4.2使用数组方法 (4.2 Using Array methods)

Converting Sets to an Array is as simple as using a spread operator ( ). You can use all the Array methods easily on Sets as well!

将集合转换为数组就像使用扩展运算符( )一样简单。 您也可以在Set上轻松使用所有Array方法!

Let’s say we have a set as shown below and we want to filter it to only contain items greater than 3.

假设我们有一个如下所示的集合,并且我们希望对其进行filter以仅包含大于3的项目。

let mySet = new Set([1,2, 3, 4, 5]);
var filtered = [...mySet].filter((x) => x > 3) // [4, 5]

5.数组解构 (5. Array destructuring)

Many times your function may return multiple values in an array. We can easily grab them by using Array destructuring.

很多时候,您的函数可能会在数组中返回多个值。 我们可以使用数组解构轻松地抓住它们。

5.1交换价值 (5.1 Swap values)

let param1 = 1;let param2 = 2;
//swap and assign param1 & param2 each others values[param1, param2] = [param2, param1];
console.log(param1) // 2console.log(param2) // 1

5.2从一个函数接收并分配多个值 (5.2 Receive and assign multiple values from a function)

In the below example, we are fetching a post at /post and related comments at /comments . Since we are using async / await , the function returns the result in an array. Using array destructuring, we can simply assign the result directly into corresponding variables.

在下面的示例中,我们在/post处获取帖子,在/post comments处获取相关/comments 。 由于我们正在使用async / await ,因此该函数将结果返回到数组中。 使用数组解构,我们可以简单地将结果直接分配给相应的变量。

async function getFullPost(){  return await Promise.all([    fetch('/post'),    fetch('/comments')  ]);}
const [post, comments] = getFullPost();

如果这有用,请单击拍手? 请点击以下几次以显示您的支持! ???? (If this was useful, please click the clap ? button down below a few times to show your support! ⬇⬇⬇ ??)

ECMAScript 2015+ (ECMAScript 2015+)

终端改进 (Terminal Improvements)

万维网 (WWW)

虚拟DOM (Virtual DOM)

React表现 (React Performance)

功能编程 (Functional Programming)

Web包装 (WebPack)

  1. (under-the-hood)

    ( )

Draft.js (Draft.js)

React And Redux: (React And Redux :)

  1. (3-page app)

    (3页应用程序)

翻译自:

转载地址:http://fcgwd.baihongyu.com/

你可能感兴趣的文章
PHP批量插入
查看>>
laravel连接sql server 2008
查看>>
Laravel框架学习笔记之任务调度(定时任务)
查看>>
Laravel 的生命周期
查看>>
Nginx
查看>>
Navicat远程连接云主机数据库
查看>>
Nginx配置文件nginx.conf中文详解(总结)
查看>>
jxl写入excel实现数据导出功能
查看>>
linux文件目录类命令|--cp指令
查看>>
.net MVC 404错误解决方法
查看>>
linux系统目录结构
查看>>
学习进度
查看>>
使用Postmark测试后端存储性能
查看>>
NSTextView 文字链接的定制化
查看>>
第五天站立会议内容
查看>>
ATMEGA16 IOport相关汇总
查看>>
JAVA基础-多线程
查看>>
面试题5:字符串替换空格
查看>>
[Codevs] 线段树练习5
查看>>
Amazon
查看>>