查看這些有用的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.pswp.cn/news/394591.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/394591.shtml
英文地址,請注明出處:http://en.pswp.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…