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 default parameter values 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 reduce 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, map) and then filter only a few items (that is, filter). 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 here.

使用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); // =&gt; 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! ⬇⬇⬇ ??)

我的其他帖子 (My Other Posts)

https://medium.com/@rajaraodv/latest

https://medium.com/@rajaraodv/latest

ECMAScript 2015+ (ECMAScript 2015+)

  1. Examples of everything *NEW* in ECMAScript 2016, 2017, and 2018

    ECMAScript 2016、2017和2018中所有* NEW *的示例

  2. Check out these useful ECMAScript 2015 (ES6) tips and tricks

    查看这些有用的ECMAScript 2015(ES6)提示和技巧

  3. 5 JavaScript “Bad” Parts That Are Fixed In ES6

    ES6中修复的5个JavaScript“不良”部分

  4. Is “Class” In ES6 The New “Bad” Part?

    ES6中的“类”是新的“不良”部分吗?

终端改进 (Terminal Improvements)

  1. How to Jazz Up Your Terminal — A Step By Step Guide With Pictures

    如何使您的终端更加爵士乐-带有图片的分步指南

  2. Jazz Up Your “ZSH” Terminal In Seven Steps — A Visual Guide

    通过七个步骤使您的“ ZSH”终端变得爵士乐—视觉指南

万维网 (WWW)

  1. A Fascinating And Messy History Of The Web And JavaScript

    Web和JavaScript的迷人历史

虚拟DOM (Virtual DOM)

  1. Inner Workings Of The Virtual DOM

    虚拟DOM的内部运作

React表现 (React Performance)

  1. Two Quick Ways To Reduce React App’s Size In Production

    两种减少React App生产规模的快速方法

  2. Using Preact Instead Of React

    使用Preact代替React

功能编程 (Functional Programming)

  1. JavaScript Is Turing Complete — Explained

    JavaScript正在完善–解释

  2. Functional Programming In JS — With Practical Examples (Part 1)

    JS中的函数式编程—结合实际示例(第1部分)

  3. Functional Programming In JS — With Practical Examples (Part 2)

    JS中的函数式编程—结合实际示例(第2部分)

  4. Why Redux Need Reducers To Be “Pure Functions”

    为什么Redux需要Reducer成为“纯功能”

Web包装 (WebPack)

  1. Webpack — The Confusing Parts

    Webpack —令人困惑的部分

  2. Webpack & Hot Module Replacement [HMR] (under-the-hood)

    Webpack和热模块更换[HMR] ( 后台 )

  3. Webpack’s HMR And React-Hot-Loader — The Missing Manual

    Webpack的HMR和React-Hot-Loader —缺少的手册

Draft.js (Draft.js)

  1. Why Draft.js And Why You Should Contribute

    为什么选择Draft.js,为什么要贡献力量

  2. How Draft.js Represents Rich Text Data

    Draft.js如何表示富文本数据

React And Redux: (React And Redux :)

  1. Step by Step Guide To Building React Redux Apps

    构建React Redux应用程序的逐步指南

  2. A Guide For Building A React Redux CRUD App (3-page app)

    构建React Redux CRUD应用程序指南 (3页应用程序)

  3. Using Middlewares In React Redux Apps

    在React Redux应用程序中使用中间件

  4. Adding A Robust Form Validation To React Redux Apps

    向React Redux应用添加强大的表单验证

  5. Securing React Redux Apps With JWT Tokens

    使用JWT令牌保护React Redux应用程序

  6. Handling Transactional Emails In React Redux Apps

    在React Redux应用程序中处理交易电子邮件

  7. The Anatomy Of A React Redux App

    React Redux应用程序剖析

  8. Why Redux Need Reducers To Be “Pure Functions”

    为什么Redux需要Reducer成为“纯功能”

  9. Two Quick Ways To Reduce React App’s Size In Production

    两种减少React App生产规模的快速方法

翻译自: https://www.freecodecamp.org/news/check-out-these-useful-ecmascript-2015-es6-tips-and-tricks-6db105590377/

查看这些有用的ECMAScript 2015(ES6)提示和技巧相关推荐

  1. ECMAScript 2015 ES6

    锋利的ES6(持续更新中-) ES6简介:   ECMAScript 6.0(以下简称ES6)是JavaScript语言的下一代标准,已经在2015年6月正式发布了.所以又称ECMAScript 20 ...

  2. 21 个非常有用的 .htaccess 提示和技巧

    Apache Web 服务器可以通过 .htaccess 文件来操作各种信息,这是一个目录级配置文件的默认名称,允许去中央化的 Web 服务器配置管理.可用来重写服务器的全局配置.该文件的目的就是为了 ...

  3. 《Access 2007开发指南(修订版)》一一1.11 额外的提示和技巧

    本节书摘来自异步社区出版社<Access 2007开发指南(修订版)>一书中的第1章,第1.11节,作者: [美]Alison Balter,更多章节内容可以访问云栖社区"异步社 ...

  4. ECMAScript 2015(ES6)规范中的promise

    ECMAScript 2015(ES6)规范中的promise – 转 概述 Promise 对象用于延迟(deferred) 计算和异步(asynchronous ) 计算..一个Promise对象 ...

  5. 使嵌入式系统调试更容易:有用的硬件和软件提示

    使嵌入式系统调试更容易:有用的硬件和软件提示 Making embedded system debug easier: useful hardware & software tips 嵌入式系 ...

  6. ECMAScript 2015~2020 语法全解析

    ECMAScript 2015~2020 语法全解析 ( ES6 ~ ES11 ) . 快速上手 => es.xiecheng.live

  7. 分享图表制作技巧_15个最有用的Windows 10提示和技巧信息图表

    分享图表制作技巧 查看最有用的Windows 10提示和技巧,以快速入门: (Look at the most useful Windows 10 Tips and Tricks for a quic ...

  8. 8个有趣的Linux提示与技巧

    我们时不时给你带来关于Linux的提示与技巧.这里我们总结了8个最有趣的提示和技巧.推荐学习Linux视频教程. 以它们的大小列出文件 如果你想要一个基于它们大小排序的文件列表,你可以使用下面的命令. ...

  9. 提示和技巧:光线跟踪最佳实践

    提示和技巧:光线跟踪最佳实践 Tips and Tricks: Ray Tracing Best Practices 本文介绍了在游戏和其他实时图形应用程序中实现光线跟踪的最佳实践.我们尽可能简短地介 ...

最新文章

  1. WireShark数据包分析数据封装
  2. js 获得明天0点时间戳_需要知道的JS的日期知识,都在这了
  3. Exchange 接收连接器(Client、Default)区别
  4. 增值税发票的种类_以及税率---财务知识工作笔记001
  5. ios 地图黑屏_ios – 导航控制器显示黑屏
  6. 车联网中如何应用大数据
  7. java resouce_Java 获取Resource目录下的文件解决办法
  8. jquery ready() 与window onload的区别
  9. 【原】数据分析/数据挖掘/机器学习---- 必读书目
  10. VideoPlayer参数
  11. Java字符串排序设计(升序排列)
  12. 定积分证明题例题_数列极限求法十五种(25个例题+推文送给微积分和数学分析同学)...
  13. 面向大众征集 “故宫·金榜题名”文创众筹大赛启动
  14. 利用Xposed+JustTrustMe绕过Android App(途牛apk)的SSL Pinning
  15. VMware vSphere7 with Tanzu 安装方案
  16. 易到CEO巩振兵被曝本周已离职 其称“在开会”
  17. android:layout_weight=1,Android中的Layout_weight(权重)详解
  18. eclipse设置pom.xml打开方式,显示dependences视图
  19. 用AS实现微信界面设计
  20. 4.4 区块链和大数据

热门文章

  1. Java架构师必备框架技能核心笔记,工作感悟
  2. 腾讯,字节,阿里,小米,京东大厂Offer拿到手软!分享一点面试小经验
  3. 真香警告!2021Android高级面试题,挥泪整理面经
  4. [学习之道] 修福不修慧,大象披璎珞; 修慧不修福,罗汉托空钵 (学习写程序,只靠补习上课吗?)...
  5. 在layui中使用 jquery 触发select 的 change事件无效
  6. 2017年读书计划(一)
  7. 23种设计模式----------建造者模式
  8. Android的Button按钮,ACTION_UP事件不触发解决方案
  9. 【转CSDN常高伟】如何学习一门新的语言
  10. 恐怖之城(深圳)系列1---K113大巴洗劫一空