Home Web Front-end JS Tutorial Summary of ES6 usage tips

Summary of ES6 usage tips

May 15, 2018 pm 02:12 PM
skills Summarize

This time I will bring you a summary of ES6 usage skills. What are the precautions when using ES6. The following is a practical case, let’s take a look.

If you know some other tips, please leave a message. I'm happy to add them.

1. Mandatory parameters

ES6 provides a default parameter value mechanism, allowing you to set default values ​​for parameters to prevent functions from being called. These parameters were not passed in.

In the following example, we write a required() function as the default value for parameters a and b. This means that if one of the parameters in a or b is not passed a value when called, the required() function will be defaulted and an error will be thrown.

const required = () => {throw new Error('Missing parameter')};
const add = (a = required(), b = required()) => a + b;
add(1, 2) //3
add(1) // Error: Missing parameter.
Copy after login

2. Powerful reduce

The reduce method of arrays is very versatile. It is generally used to reduce each item in an array to a single value. But you can do more with it.

2.1 Use reduce to implement map and filter at the same time

Suppose there is a sequence now, and you want to update each item of it (map function) and then filter out a part ( filter function). If you use map first and then filter, you need to iterate through the array twice.

In the code below, we double the values ​​in the sequence and then select those numbers greater than 50. Notice how we use reduce very efficiently to complete both the map and filter methods?

const numbers = [10, 20, 30, 40];
const doubledOver50 = numbers.reduce((finalList, num) => {
 num = num * 2; 
 if (num > 50) {
  finalList.push(num);
 }
 return finalList;
}, []);
doubledOver50; // [60, 80]
Copy after login

2.2 Use reduce to replace map and filter

If you read the above code carefully, you should be able to understand that reduce can replace map and filter.

2.3 Use reduce to match parentheses

Another use of reduce is to be able to match parentheses in a given string. For a string containing parentheses, we need to know whether the number of (and) is consistent, and whether (appears before).

In the following code we can easily solve this problem using reduce. We only need to declare a counter variable first, with the initial value being 0. Counter increases by one when encountering (, counter decreases by one when encountering). If the number of left and right brackets matches, the final result is 0.

//Returns 0 if balanced.
const isParensBalanced = (str) => {
 return str.split('').reduce((counter, char) => {
  if(counter < 0) { //matched ")" before "("
   return counter;
  } else if(char === &#39;(&#39;) {
   return ++counter;
  } else if(char === &#39;)&#39;) {
   return --counter;
  } else { //matched some other char
   return counter;
  }
  
 }, 0); //<-- starting value of the counter
}
isParensBalanced(&#39;(())&#39;) // 0 <-- balanced
isParensBalanced(&#39;(asdfds)&#39;) //0 <-- balanced
isParensBalanced(&#39;(()&#39;) // 1 <-- not balanced
isParensBalanced(&#39;)(&#39;) // -1 <-- not balanced
Copy after login

2.4 Count the number of identical items in an array

Many times, you want to count the number of recurring items in an array and then represent them with an object. Then you can use the reduce method to process this array.

The following code will count the number of each type of car and then represent the total number with an object.

var cars = [&#39;BMW&#39;,&#39;Benz&#39;, &#39;Benz&#39;, &#39;Tesla&#39;, &#39;BMW&#39;, &#39;Toyota&#39;];
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 }
Copy after login

There are so many other uses for reduce. I recommend you read MDN’s related code examples.

3. Object destructuring

3.1 Delete unnecessary attributes

Sometimes you don’t You want to preserve certain object properties, perhaps because they contain sensitive information or are just too big. You might be able to enumerate the entire object and delete them, but really you just assign the useless properties to variables, and then pass the useful parts you want to keep as the remaining parameters.

In the following code, we want to delete the _internal and tooBig parameters. We can assign them to the internal and tooBig variables, and then store the remaining properties in cleanObject for later use.

let {_internal, tooBig, ...cleanObject} = {el1: &#39;1&#39;, _internal:"secret", tooBig:{}, el2: &#39;2&#39;, el3: &#39;3&#39;};
console.log(cleanObject); // {el1: &#39;1&#39;, el2: &#39;2&#39;, el3: &#39;3&#39;}
Copy after login

3.2 Deconstructing nested objects in function parameters

In the following code, engine is an object nested in the object car . If we are interested in the vin attribute of engine, we can easily get it using destructuring assignment.

var car = {
 model: &#39;bmw 2018&#39;,
 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
Copy after login

3.3 Merging Objects

ES6 brings the extended operator(...). It's typically used to destructure arrays, but you can also use it with objects.

Next, we use the spread operator to expand a new object. The attribute values ​​in the second object will overwrite the attribute values ​​of the first object. For example, b and c of object2 will overwrite the attributes of the same name of 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 merged
console.log(merged) // {a:1, b:30, c:40, d:50}
Copy after login

4. Sets

4.1 Use Set to implement array deduplication

In ES6 , because Set only stores unique values, you can use Set to remove duplicates.

let arr = [1, 1, 2, 2, 3, 3];
let deduped = [...new Set(arr)] // [1, 2, 3]
Copy after login

4.2 对Set使用数组方法

使用扩展运算符就可以简单的将Set转换为数组。所以你可以对Set使用Array的所有原生方法。

比如我们想要对下面的Set进行filter操作,获取大于3的项。

let mySet = new Set([1,2, 3, 4, 5]);
var filtered = [...mySet].filter((x) => x > 3) // [4, 5]
Copy after login

5. 数组解构

有时候你会将函数返回的多个值放在一个数组里。我们可以使用数组解构来获取其中每一个值。

5.1 数值交换

let param1 = 1;
let param2 = 2;
//swap and assign param1 & param2 each others values
[param1, param2] = [param2, param1];
console.log(param1) // 2
console.log(param2) // 1
Copy after login

5.2 接收函数返回的多个结果

在下面的代码中,我们从/post中获取一个帖子,然后在/comments中获取相关评论。由于我们使用的是async/await,函数把返回值放在一个数组中。而我们使用数组解构后就可以把返回值直接赋给相应的变量。

async function getFullPost(){
 return await Promise.all([
  fetch(&#39;/post&#39;),
  fetch(&#39;/comments&#39;)
 ]);
}
const [post, comments] = getFullPost();
Copy after login

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

vue实现移动端微信公众号步骤详解

JS设计模式中链式调用使用解析

The above is the detailed content of Summary of ES6 usage tips. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Summarize the usage of system() function in Linux system Summarize the usage of system() function in Linux system Feb 23, 2024 pm 06:45 PM

Summary of the system() function under Linux In the Linux system, the system() function is a very commonly used function, which can be used to execute command line commands. This article will introduce the system() function in detail and provide some specific code examples. 1. Basic usage of the system() function. The declaration of the system() function is as follows: intsystem(constchar*command); where the command parameter is a character.

How to use Go language for quantitative financial analysis? How to use Go language for quantitative financial analysis? Jun 11, 2023 am 08:51 AM

In the field of modern finance, with the rise of data science and artificial intelligence technology, quantitative finance has gradually become an increasingly important direction. As a statically typed programming language that can efficiently process data and deploy distributed systems, Go language has gradually attracted attention in the field of quantitative finance. This article will introduce how to use the Go language to perform quantitative financial analysis. The specific content is as follows: Obtaining financial data First, we need to obtain financial data. The network programming capabilities of Go language are very powerful and can be used to obtain various financial data. Compare

How to use Go language for data mining? How to use Go language for data mining? Jun 10, 2023 am 08:39 AM

With the rise of big data and data mining, more and more programming languages ​​have begun to support data mining functions. As a fast, safe and efficient programming language, Go language can also be used for data mining. So, how to use Go language for data mining? Here are some important steps and techniques. Data Acquisition First, you need to obtain the data. This can be achieved through various means, such as crawling information on web pages, using APIs to obtain data, reading data from databases, etc. Go language comes with rich HTTP

How to write the minimum spanning tree algorithm using C# How to write the minimum spanning tree algorithm using C# Sep 19, 2023 pm 01:55 PM

How to use C# to write the minimum spanning tree algorithm. The minimum spanning tree algorithm is an important graph theory algorithm, which is used to solve the connectivity problem of graphs. In computer science, a minimum spanning tree refers to a spanning tree of a connected graph in which the sum of the weights of all edges of the spanning tree is the smallest. This article will introduce how to use C# to write the minimum spanning tree algorithm and provide specific code examples. First, we need to define a graph data structure to represent the problem. In C#, you can use an adjacency matrix to represent a graph. An adjacency matrix is ​​a two-dimensional array in which each element represents

How to use PHP to develop simple SEO optimization functions How to use PHP to develop simple SEO optimization functions Sep 20, 2023 pm 04:18 PM

How to use PHP to develop simple SEO optimization functions SEO (SearchEngineOptimization), or search engine optimization, refers to improving the website's ranking in search engines by improving the structure and content of the website, thereby obtaining more organic traffic. In website development, how to use PHP to implement simple SEO optimization functions? This article will introduce some commonly used SEO optimization techniques and specific code examples to help developers implement SEO optimization in PHP projects. 1. Friendly to use

How to use nginx to prevent hotlinking How to use nginx to prevent hotlinking Jun 11, 2023 pm 01:25 PM

With the popularity of the Internet, more and more websites provide external link functions for pictures, videos and other resources. However, this external link function is easy to be stolen. Hotlinking means that other websites use pictures, videos and other resources on your website to directly display these resources on their own website through the reference address instead of downloading them to their own server. In this way, hotlink websites can use your website's traffic and bandwidth resources for free, which wastes resources and affects website speed. To address this problem, Nginx can be used to prevent hotlinking. Nginx is

How to use the divide and conquer algorithm in C++ How to use the divide and conquer algorithm in C++ Sep 20, 2023 pm 03:19 PM

How to use the divide-and-conquer algorithm in C++ The divide-and-conquer algorithm is a method that decomposes a problem into several sub-problems and then combines the solutions to the sub-problems to obtain a solution to the original problem. It has a wide range of applications and can be used to solve various types of problems, including mathematical problems, sorting problems, graph problems, etc. This article will introduce how to use the divide and conquer algorithm in C++ and provide specific code examples. 1. Basic idea The basic idea of ​​the divide-and-conquer algorithm is to decompose a large problem into several smaller sub-problems, solve each sub-problem recursively, and finally merge the sub-problems.

Easy solution: A complete guide to pip mirror source usage techniques Easy solution: A complete guide to pip mirror source usage techniques Jan 16, 2024 am 10:31 AM

One-click solution: Quickly master the usage skills of pip mirror source Introduction: pip is the most commonly used package management tool for Python, which can easily install, upgrade and manage Python packages. However, due to well-known reasons, using the default mirror source to download the installation package is slower. In order to solve this problem, we need to use a domestic mirror source. This article will introduce how to quickly master the usage skills of pip mirror source and provide specific code examples. Before you start, understand the concept of pip mirror source.

See all articles