This article introduces 8 very useful functions in ES2019. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
#The ES2019 specification is a small extension to JavaScript, but still brings some interesting features. This article shows you eight ES2019 features that can make your development easier.
String.prototype.trimStart() and String.prototype.trimEnd()
Sometimes we need to deal with extra spaces when processing strings. ES2020 adds two functions: .trimStart()
and trimEnd()
methods to help you handle these chores.
They all can help you trim or remove spaces in a given string. trimStart()
Remove all spaces at the beginning of the string. trimEnd()
will remove all spaces at the end of the string. But what if you want to remove the spaces on both sides?
There are two options. The first is to use both ES2019 features simultaneously. The second is to use another string method trim()
. Both methods will give you the results you want.
// String.prototype.trimStart() 例子: // 处理不带空格的字符串: 'JavaScript'.trimStart() // Output: //'JavaScript' // 处理以空格开头的字符串: ' JavaScript'.trimStart() // Output: //'JavaScript' // 两边都留有空格的字符串 ' JavaScript '.trimStart() // Output: //'JavaScript ' // 以空格结尾的字符串 'JavaScript '.trimStart() // Output: //'JavaScript ' // String.prototype.trimEnd() 例子: // 处理不带空格的字符串: 'JavaScript'.trimEnd() // Output: //'JavaScript' // 处理以空格开头的字符串: ' JavaScript'.trimEnd() // Output: //' JavaScript' // 两边都留有空格的字符串 ' JavaScript '.trimEnd() // Output: //' JavaScript' // 以空格结尾的字符串 'JavaScript '.trimEnd() // Output: //'JavaScript'
Function.prototype.toString()
The toString()
method of function has been around for a while. What it does is allows you to print the code of the function. ES2019 differs in the way it handles comments and special characters such as spaces.
In the past, the toString()
method removed comments and whitespace. So the printed version of the function may look different from the original code. This will no longer happen with ES2019. The value it returns will match the original value, including comments and special characters.
// ES2019 之前: function myFunc/* is this really a good name? */() { /* Now, what to do? */ } myFunc.toString() // Output: // "function myFunc() {}" // ES2019: function myFunc/* is this really a good name? */() { /* Now, what to do? */ } myFunc.toString() // Output: // "function myFunc/* is this really a good name? */() { // /* Now, what to do? */ // }"
Array.prototype.flat() and Array.prototype.flatMap()
Arrays are one of the fundamental building blocks of JavaScript. They sometimes cause a lot of problems. This is especially true when you have to deal with multidimensional arrays. Even a seemingly simple task like converting a multidimensional array to one dimension can be difficult.
The good news is that two features of ES2019 make this easier. The first is the flat()
method. When used on a multidimensional array, it will be converted to one dimension. By default, flat()
will only flatten the array one level.
But the page can specify the level and pass it as a parameter when calling. You can also use Infinity
if you're not sure how many levels you need.
// 创建一个数组: const myArray = ['JavaScript', ['C', 'C++', ['Assembly', ['Bytecode']]]] // 展平一级: let myFlatArray = myArray.flat(1) // 输出: console.log(myFlatArray) // Output: // [ 'JavaScript', 'C', 'C++', [ 'Assembly', [ 'Bytecode' ] ] ] // 用参数 Infinity 展平: let myInfiniteFlatArray = myArray.flat(Infinity) // 输出: console.log(myInfiniteFlatArray) // Output: // [ 'JavaScript', 'C', 'C++', 'Assembly', 'Bytecode' ]
Array.prototype.flatMap()
In addition to the flat()
method, there is also flatMap()
. Think of it as an advanced version of flat()
. The difference is that the flatMap()
method combines flat()
with map()
. The callback function can be called when flattening the array.
This allows every element in the original array to be used during the flattening process. This is convenient when you want to modify the contents of an array while flattening it.
// 创建数组: const myArray = ['One word', 'Two words', 'Three words'] // 用 map() 将数组中的所有字符串拆分为单词: // 注意:这将会创建多维数组。 const myMappedWordArray = myArray.map(str => str.split(' ')) console.log(myMappedWordArray) // Output: // [ [ 'One', 'word' ], [ 'Two', 'words' ], [ 'Three', 'words' ] ] // flatMap() 的例子: const myArray = ['One word', 'Two words', 'Three words'] // 用 map() 将数组中的所有字符串拆分为单词: // 注意:这将会创建多维数组。 const myFlatWordArray = myArray.flatMap(str => str.split(' ')) console.log(myFlatWordArray) // Output: // [ 'One', 'word', 'Two', 'words', 'Three', 'words' ]
Object.fromEntries()
When you need to convert an object into an array, you can use entries()
to complete it. But it is difficult to do the reverse operation. ES2019 provides fromEntries()
to easily solve this problem.
The function of this method is very simple. It takes an iterable form of key-value pairs, such as an array or Map, and converts it to an object.
// 把数组转换为对象: // 创建数组: const myArray = [['name', 'Joe'], ['age', 33], ['favoriteLanguage', 'JavaScript']] const myObj = Object.fromEntries(myArray) console.log(myObj) // Output: // { // name: 'Joe', // age: 33, // favoriteLanguage: 'JavaScript' // } // 把 Map 转换为对象: // 创建 map: const myMap = new Map( [['name', 'Spike'], ['species', 'dog'], ['age', 3]] ) const myObj = Object.fromEntries(myMap) console.log(myObj) // Output: // { // name: 'Spike', // species: 'dog', // age: 3 // }
Optional catch binding
When previously using try ... catch
, binding must also be used. Even if the exception is not used, you must pass it as a parameter. In ES2019, if you don't want to use the exception, you can use a catch block without parameters.
// ES2019 之前: try { // Do something. } catch (e) { //忽略必需的e参数 //如果你不想用它,也应该保留。 } // ES2019: try { // Do something. } catch { // 不需要添加任何参数 }
Correctly formatted JSON.stringify()
In the past, when using JSON.stringify( )
, you get a malformed Unicode string. The encoding section from U D800 to U DFFF will become "�". What's worse is that there is no way to change these wrong characters back to their original form.
ES2019 Fixed the JSON.stringify()
method. It is now possible to classify those problematic code snippets and convert them back to their original representation.
Symbol.prototype.description
Symbol is a new data type introduced in ES2015 (ES6). They are often used to identify object properties. ES2019 added the description
attribute. This property is read-only and its value cannot be changed. It is used to return the description of the given symbol.
Two points should be kept in mind. First, descriptions are not required when creating symbols, but are optional. So when you try to access description
, you may get anything except undefined
. If you try to access a symbol description without a description, you will get the undefined
(undefined) message.
第二点是 description
是对符号本身的描述。它不是符号的标识符。这意味着你不能使用现有的描述(即 description
属性的值)来访问现有的符号。它只是为了更容易识别正在你正在使用的符号。
说明:创建新的符号时,可以通过将一些字符串作为参数传递给 Symbol()
对象来添加描述。如果留空,description
将会是 undefined
。
// 创建带有描述的 Symbol: // 创建 Symbol 并添加描述: //注意:描述是"My first symbol." const mySymbol = Symbol('My first symbol.') // 输出 description 属性的值: console.log(mySymbol.description) // Output: // 'My first symbol.' // 读取不存在的 Symbol: console.log(Symbol().description) // Output: // undefined // 读取定义为空字符串的描述: console.log(Symbol('').description) // Output: // ''
Symbol.prototype.toString()
toString()
方法提供了另一种读取符号描述的方式。它的缺点是在返回的字符串中还包含 Symbol()
。另一个区别是 toString()
方法永远不会返回不存在的undefined
描述。
使用 description
的另一个原因是:如果你有一个没有说明的 Symbol 并用了 toString()
方法,仍将得到 Symbol()
部分。如果描述为空字符串,也将获得此信息。这样就基本上不可能区分不存在的描述和用作描述的空字符串。
// 创建带有描述的 Symbol: const mySymbol = Symbol('REAMDE.') // 输出 description 属性的值: console.log(mySymbol.toString()) // Output: // 'Symbol(REAMDE.)' // 读取不存在的 Symbol: console.log(Symbol().toString()) // Output: // 'Symbol()' // 读取定义为空字符串的描述: console.log(Symbol('').toString()) // Output: // 'Symbol()'
更多编程相关知识,可访问:编程入门!!
The above is the detailed content of Share 8 useful features worth collecting in ES2019. For more information, please follow other related articles on the PHP Chinese website!

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.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing


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

Dreamweaver Mac version
Visual web development tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

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.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

WebStorm Mac version
Useful JavaScript development tools