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

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! ⬇⬇⬇ ??)

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/

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/394591.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

inputstream转fileinputstream对象_FileInputStream类:文件字节输入流

API ----IO ----字节输入输出流练习 java.lang.Object 继承者 java.io.InputStream 继承者 java.io.FileInputStreampublic FileInputStream类速查速记&#xff1a;直接包装File用于从记事本中读数据 in是针对java来说的&#xff0c;从记事本读入到java* 构造方法&#xff1a;…

IBM将推NVMe存储解决方案

先前&#xff0c;IBM曾对外宣称将开发新的NVMe解决方案&#xff0c;并推动行业参与者进一步探索新协议&#xff0c;以支持更快的数据传输。周日&#xff0c;IBM表示新的语言协议——NVMe&#xff08;非易失性存储器&#xff09;正在逐步取代SAS和SATA等旧有的固态硬盘存储标准。…

html5中3个盒子怎样设置,Web前端开发任务驱动式教程(HTML5+CSS3+JavaScript)任务10 盒子模型及应用.pptx...

第五单元 盒子模型任务10 盒子模型及应用学习目标盒子模型的概念掌握边框的设置内边距的设置外边距的设置学习目标了解:利用盒子模型布局网页的优势任务目标实战演练——制作古诗文欣赏网页强化训练——制作散文赏析网页知识准备1. 盒子模型的概念知识准备1. 盒子模型的概念CSS…

SQL手工注入入门级笔记(更新中)

一、字符型注入 针对如下php代码进行注入&#xff1a; $sql"select user_name from users where name$_GET[name]"; 正常访问URL:http://url/xxx.php?nameadmin 此时实际数据库语句: select user_name from users where nameadmin 利用以上结果可想到SQL注入构造语句…

materialize_使用Materialize快速介绍材料设计

materialize什么是材料设计&#xff1f; (What is Material Design?) Material Design is a design language created by Google. According to material.io, Material Design aims to combine:Material Design是Google创建的一种设计语言。 根据material.io &#xff0c;Mate…

python处理完数据导入数据库_python 将execl测试数据导入数据库操作

import xlrd import pymysql # 打开execl表 book xlrd.open_workbook(XXXX测试用例.xlsx) sheet book.sheet_by_name(Sheet1) # print(sheet.nrows) # 创建mysql连接 conn pymysql.connect( host127.0.0.1, userroot, password123456, dbdemo1, port3306, charsetutf8 ) # 获…

增删改查类

<?php // 所有数据表的基类 abstract class Model {protected $tableName "";protected $pdo "";protected $sql"";function __construct() {$pdo new PDO( "mysql:host" . DB_HOST . ";dbname" . DB_NAME, DB_USERN…

html网页和cgi程序编程,CGI 编程方式学习

1.大家都知道CGI是通用网关接口&#xff0c;可以用来编写动态网页。而且CGI可以用很多种语言来写&#xff0c;用perl来编写最常见&#xff0c;我这里就是用perl来编写做例子。讲到编写CGI编程方式&#xff0c;编写CGI有两程编程风格。(1)功能型编程(function-oriented style)这…

20175305张天钰 《java程序设计》第四周课下测试总结

第四周课下测试总结 错题 某方法在父类的访问权限是public&#xff0c;则子类重写时级别可以是protected。 A .true B .false 正确答案&#xff1a;B 解析&#xff1a;书P122&#xff1a;子类不允许降低方法的访问权限&#xff0c;但可以提高访问权限。 复杂题&#xff08;易错…

强化学习q学习求最值_通过Q学习更深入地学习强化学习

强化学习q学习求最值by Thomas Simonini通过托马斯西蒙尼(Thomas Simonini) 通过Q学习更深入地学习强化学习 (Diving deeper into Reinforcement Learning with Q-Learning) This article is part of Deep Reinforcement Learning Course with Tensorflow ?️. Check the syl…

BZOJ 1113: [Poi2008]海报PLA

1113: [Poi2008]海报PLA Time Limit: 10 Sec Memory Limit: 162 MBSubmit: 1025 Solved: 679[Submit][Status][Discuss]Description N个矩形,排成一排. 现在希望用尽量少的矩形海报Cover住它们. Input 第一行给出数字N,代表有N个矩形.N在[1,250000] 下面N行,每行给出矩形的长…

Python自动化运维之常用模块—OS

os模块的作用&#xff1a;  os&#xff0c;语义为操作系统&#xff0c;所以肯定就是操作系统相关的功能了&#xff0c;可以处理文件和目录这些我们日常手动需要做的操作&#xff0c;就比如说&#xff1a;显示当前目录下所有文件/删除某个文件/获取文件大小……  另外&#…

opengl三维图形图形颜色_【图形学基础】基本概念

右手坐标系。类似OpenGL遵循的右手坐标系&#xff1a;首先它是三维的笛卡尔坐标系&#xff1a;原点在屏幕正中&#xff0c;x轴从屏幕左向右&#xff0c;最左是-1&#xff0c;最右是1&#xff1b;y轴从屏幕下向上&#xff0c;最下是-1&#xff0c;最上是1&#xff1b;z轴从屏幕里…

xp职称计算机考试题库,2015年职称计算机考试XP题库.doc

2015年职称计算机考试XP题库.doc (7页)本资源提供全文预览&#xff0c;点击全文预览即可全文预览,如果喜欢文档就下载吧&#xff0c;查找使用更方便哦&#xff01;9.90 积分&#xfeff;2015年职称计算机考试XP题库职称计算机考试考点精编&#xff1a;工具栏的设置与操作XP中将…

Java基础学习-Path环境变量的配置

1.为什么要进行Path环境变量的配置程序的编译和执行需要使用到javac和java命令&#xff0c;所以只能在bin目录下写程序&#xff0c;而实际开发中&#xff0c;我们不可能将程序全部写到bin目录下&#xff0c;所以我们不许让javac和java命令在任意目录下都能够被访问。这时候&…

rails 共享变量_如何将Rails实例变量传递给Vue组件

rails 共享变量by Gareth Fuller由Gareth Fuller 如何将Rails实例变量传递给Vue组件 (How to pass Rails instance variables into Vue components) I’m currently working with a legacy Rails application. We are slowly transitioning the front-end from Rails views to…

Leetcode: Counting Bits

Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1s in their binary representation and return them as an array.Example: For num 5 you should return [0,1,1,2,1,2].Follow up:It is very easy to c…

第一个python爬虫_Python爬虫01——第一个小爬虫

Python小爬虫——贴吧图片的爬取 在对Python有了一定的基础学习后&#xff0c;进行贴吧图片抓取小程序的编写。 目标&#xff1a; 首先肯定要实现图片抓取这个基本功能 然后实现对用户所给的链接进行抓取 最后要有一定的交互&#xff0c;程序不能太傻吧 一、页面获取 要让pytho…

Mac下,如何把项目托管到Github上(Github Desktop的使用)

在上一篇中&#xff0c;详细讲解了使用X-code和终端配合上传代码的方法&#xff0c;这种方法比较传统&#xff0c;中间会有坑&#xff0c;英文看起来也费劲&#xff0c;不过Github官方提供了一个Mac版的客户端&#xff0c;如下图&#xff1a; 附上下载链接&#xff1a;传送门 下…

计算机网络英文面试题,计算机网络面试题整理

GET和POST的区别&#xff1f;GET和POST方法没有实质上区别&#xff0c;只是报文格式不同。GET和POST是HTTP协议中的两种请求方法。而 HTTP 协议是基于 TCP/IP 的应用层协议&#xff0c;无论 GET 还是 POST&#xff0c;用的都是同一个传输层协议&#xff0c;所以在传输上&#x…