What are the precautions for using ES6?
This time I will bring you some precautions when using ES6. The following is a practical case, let’s take a look.
ES6 has been out for several years, and many new features can be cleverly used in projects. I want to list some of them in the hope that they will be useful to you.
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 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 === '(') { return ++counter; } else if(char === ')') { return --counter; } else { //matched some other char return counter; } }, 0); //<-- starting value of the counter } isParensBalanced('(())') // 0 <-- balanced isParensBalanced('(asdfds)') //0 <-- balanced isParensBalanced('(()') // 1 <-- not balanced isParensBalanced(')(') // -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 = ['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 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: '1', _internal:"secret", tooBig:{}, el2: '2', el3: '3'}; console.log(cleanObject); // {el1: '1', el2: '2', el3: '3'}
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: '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 Merging Objects
ES6 brings the spread 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 Using array methods on 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('/post'), fetch('/comments') ]); } const [post, comments] = getFullPost();
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
The above is the detailed content of What are the precautions for using ES6?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Lucky bag activities on Douyin have always been popular among users. By participating, you can not only get various discounts and gifts, but also have the chance to win big prizes. However, newbies may not understand how to draw lucky bags effectively and increase their chances of winning. This article will share with you some tips for drawing lucky bags on Douyin to help you better enjoy the fun of drawing and increase the possibility of winning big prizes. 1. Choose popular lucky bag recommendations and follow the official website: On the Douyin platform, the official often launches some popular lucky bag activities, which can often be seen on the homepage or related channels. These events are usually very popular and the prizes are generous. Therefore, it is a wise move to pay attention to official recommendations. Before opening the lucky bag, it is recommended that you read the comments and reviews of other users. By understanding other people’s lottery winning experiences and opinions on lucky bags

Win11 Tips Sharing: One trick to skip Microsoft account login Windows 11 is the latest operating system launched by Microsoft, with a new design style and many practical functions. However, for some users, having to log in to their Microsoft account every time they boot up the system can be a bit annoying. If you are one of them, you might as well try the following tips, which will allow you to skip logging in with a Microsoft account and enter the desktop interface directly. First, we need to create a local account in the system to log in instead of a Microsoft account. The advantage of doing this is

In C language, it represents a pointer, which stores the address of other variables; & represents the address operator, which returns the memory address of a variable. Tips for using pointers include defining pointers, dereferencing pointers, and ensuring that pointers point to valid addresses; tips for using address operators & include obtaining variable addresses, and returning the address of the first element of the array when obtaining the address of an array element. A practical example demonstrating the use of pointer and address operators to reverse a string.

We often create and edit tables in excel, but as a novice who has just come into contact with the software, how to use excel to create tables is not as easy as it is for us. Below, we will conduct some drills on some steps of table creation that novices, that is, beginners, need to master. We hope it will be helpful to those in need. A sample form for beginners is shown below: Let’s see how to complete it! 1. There are two methods to create a new excel document. You can right-click the mouse on a blank location on the [Desktop] - [New] - [xls] file. You can also [Start]-[All Programs]-[Microsoft Office]-[Microsoft Excel 20**] 2. Double-click our new ex

Oracle database query skills: To obtain only one piece of duplicate data, specific code examples are required. In actual database queries, we often encounter situations where we need to obtain the only piece of data from duplicate data. This article will introduce how to use Oracle database techniques to obtain only one record in duplicate data, and provide specific code examples. Scenario Description Suppose we have a table named employee, which contains employee information. There may be duplicate employee information. We need to find all duplicates

VSCode (Visual Studio Code) is an open source code editor developed by Microsoft. It has powerful functions and rich plug-in support, making it one of the preferred tools for developers. This article will provide an introductory guide for beginners to help them quickly master the skills of using VSCode. In this article, we will introduce how to install VSCode, basic editing operations, shortcut keys, plug-in installation, etc., and provide readers with specific code examples. 1. Install VSCode first, we need

Title: PHP Programming Tips: How to Jump to a Web Page within 3 Seconds In web development, we often encounter situations where we need to automatically jump to another page within a certain period of time. This article will introduce how to use PHP to implement programming techniques to jump to a page within 3 seconds, and provide specific code examples. First of all, the basic principle of page jump is realized through the Location field in the HTTP response header. By setting this field, the browser can automatically jump to the specified page. Below is a simple example demonstrating how to use P

Win11 tricks revealed: How to bypass Microsoft account login Recently, Microsoft launched a new operating system Windows11, which has attracted widespread attention. Compared with previous versions, Windows 11 has made many new adjustments in terms of interface design and functional improvements, but it has also caused some controversy. The most eye-catching point is that it forces users to log in to the system with a Microsoft account. For some users, they may be more accustomed to logging in with a local account and are unwilling to bind their personal information to a Microsoft account.
