by rajaraodv
通过rajaraodv
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.
如果您知道其他提示,请在评论中让我知道,我们很乐意添加它们。
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.
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]
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可以用于过滤或映射项目! ?
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
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 此处列出的示例。
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'}
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
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}
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]
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]
Many times your function may return multiple values in an array. We can easily grab them by using Array destructuring.
很多时候,您的函数可能会在数组中返回多个值。 我们可以使用数组解构轻松地抓住它们。
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
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();
https://medium.com/@rajaraodv/latest
https://medium.com/@rajaraodv/latest
Examples of everything *NEW* in ECMAScript 2016, 2017, and 2018
Check out these useful ECMAScript 2015 (ES6) tips and tricks
How to Jazz Up Your Terminal — A Step By Step Guide With Pictures
Functional Programming In JS — With Practical Examples (Part 1)
Functional Programming In JS — With Practical Examples (Part 2)
Webpack & Hot Module Replacement [HMR] (under-the-hood)
Webpack和热模块更换[HMR] ( 后台 )
A Guide For Building A React Redux CRUD App (3-page app)
构建React Redux CRUD应用程序指南 (3页应用程序)