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()
函數設置為a
和b
參數的默認值。 這意味著,如果未傳遞a
或b
,則會調用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.
在下面的示例中,我們要刪除_internal
和tooBig
屬性。 我們可以將它們分配給_internal
和tooBig
變量,并將剩余的變量存儲在* 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
對象的嵌套對象。 例如,如果我們對engine
的vin
屬性感興趣,我們可以輕松地對其進行分解,如下所示。
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 object2
override 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+)
Examples of everything *NEW* in ECMAScript 2016, 2017, and 2018
ECMAScript 2016、2017和2018中所有* NEW *的示例
Check out these useful ECMAScript 2015 (ES6) tips and tricks
查看這些有用的ECMAScript 2015(ES6)提示和技巧
5 JavaScript “Bad” Parts That Are Fixed In ES6
ES6中修復的5個JavaScript“不良”部分
Is “Class” In ES6 The New “Bad” Part?
ES6中的“類”是新的“不良”部分嗎?
終端改進 (Terminal Improvements)
How to Jazz Up Your Terminal — A Step By Step Guide With Pictures
如何使您的終端更加爵士樂-帶有圖片的分步指南
Jazz Up Your “ZSH” Terminal In Seven Steps — A Visual Guide
通過七個步驟使您的“ ZSH”終端變得爵士樂—視覺指南
萬維網 (WWW)
A Fascinating And Messy History Of The Web And JavaScript
Web和JavaScript的迷人歷史
虛擬DOM (Virtual DOM)
Inner Workings Of The Virtual DOM
虛擬DOM的內部運作
React表現 (React Performance)
Two Quick Ways To Reduce React App’s Size In Production
兩種減少React App生產規模的快速方法
Using Preact Instead Of React
使用Preact代替React
功能編程 (Functional Programming)
JavaScript Is Turing Complete — Explained
JavaScript正在完善–解釋
Functional Programming In JS — With Practical Examples (Part 1)
JS中的函數式編程—結合實際示例(第1部分)
Functional Programming In JS — With Practical Examples (Part 2)
JS中的函數式編程—結合實際示例(第2部分)
Why Redux Need Reducers To Be “Pure Functions”
為什么Redux需要Reducer成為“純功能”
Web包裝 (WebPack)
Webpack — The Confusing Parts
Webpack —令人困惑的部分
Webpack & Hot Module Replacement [HMR] (under-the-hood)
Webpack和熱模塊更換[HMR] ( 后臺 )
Webpack’s HMR And React-Hot-Loader — The Missing Manual
Webpack的HMR和React-Hot-Loader —缺少的手冊
Draft.js (Draft.js)
Why Draft.js And Why You Should Contribute
為什么選擇Draft.js,為什么要貢獻力量
How Draft.js Represents Rich Text Data
Draft.js如何表示富文本數據
React And Redux: (React And Redux :)
Step by Step Guide To Building React Redux Apps
構建React Redux應用程序的逐步指南
A Guide For Building A React Redux CRUD App (3-page app)
構建React Redux CRUD應用程序指南 (3頁應用程序)
Using Middlewares In React Redux Apps
在React Redux應用程序中使用中間件
Adding A Robust Form Validation To React Redux Apps
向React Redux應用添加強大的表單驗證
Securing React Redux Apps With JWT Tokens
使用JWT令牌保護React Redux應用程序
Handling Transactional Emails In React Redux Apps
在React Redux應用程序中處理交易電子郵件
The Anatomy Of A React Redux App
React Redux應用程序剖析
Why Redux Need Reducers To Be “Pure Functions”
為什么Redux需要Reducer成為“純功能”
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/