search
HomeWeb Front-endJS TutorialSummary of ES6 usage tips

Summary of ES6 usage tips

May 15, 2018 pm 02:12 PM
skillsSummarize

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.

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]

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

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 }

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;}

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

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}

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]

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]

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

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();

相信看了本文案例你已经掌握了方法,更多精彩请关注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
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
The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

See all articles

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

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!