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 <p style="text-align: left;"><strong>2.4 Count the number of identical items in an array</strong></p><p style="text-align: left;">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. </p><p style="text-align: left;">The following code will count the number of each type of car and then represent the total number with an object. </p><pre class="brush:php;toolbar:false">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!

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Linux new version
SublimeText3 Linux latest version

SublimeText3 Chinese version
Chinese version, very easy to use

Atom editor mac version download
The most popular open source editor

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