Table of Contents
String.prototype.trimStart() and String.prototype.trimEnd()
Function.prototype.toString()
Array.prototype.flat() and Array.prototype.flatMap()
Array.prototype.flatMap()
Object.fromEntries()
Optional catch binding
Correctly formatted JSON.stringify()
Symbol.prototype.description
Symbol.prototype.toString()
Home Web Front-end JS Tutorial Share 8 useful features worth collecting in ES2019

Share 8 useful features worth collecting in ES2019

Apr 23, 2021 pm 07:09 PM
javascript front end

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.

Share 8 useful features worth collecting in ES2019

#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'
Copy after login

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? */
// }"
Copy after login

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' ]
Copy after login

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' ]
Copy after login

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
// }
Copy after login

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 {
  // 不需要添加任何参数
}
Copy after login

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:
// ''
Copy after login

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()'
Copy after login

更多编程相关知识,可访问:编程入门!!

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!

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)

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

PHP and Vue: a perfect pairing of front-end development tools PHP and Vue: a perfect pairing of front-end development tools Mar 16, 2024 pm 12:09 PM

PHP and Vue: a perfect pairing of front-end development tools. In today's era of rapid development of the Internet, front-end development has become increasingly important. As users have higher and higher requirements for the experience of websites and applications, front-end developers need to use more efficient and flexible tools to create responsive and interactive interfaces. As two important technologies in the field of front-end development, PHP and Vue.js can be regarded as perfect tools when paired together. This article will explore the combination of PHP and Vue, as well as detailed code examples to help readers better understand and apply these two

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Questions frequently asked by front-end interviewers Questions frequently asked by front-end interviewers Mar 19, 2024 pm 02:24 PM

In front-end development interviews, common questions cover a wide range of topics, including HTML/CSS basics, JavaScript basics, frameworks and libraries, project experience, algorithms and data structures, performance optimization, cross-domain requests, front-end engineering, design patterns, and new technologies and trends. . Interviewer questions are designed to assess the candidate's technical skills, project experience, and understanding of industry trends. Therefore, candidates should be fully prepared in these areas to demonstrate their abilities and expertise.

Is Django front-end or back-end? check it out! Is Django front-end or back-end? check it out! Jan 19, 2024 am 08:37 AM

Django is a web application framework written in Python that emphasizes rapid development and clean methods. Although Django is a web framework, to answer the question whether Django is a front-end or a back-end, you need to have a deep understanding of the concepts of front-end and back-end. The front end refers to the interface that users directly interact with, and the back end refers to server-side programs. They interact with data through the HTTP protocol. When the front-end and back-end are separated, the front-end and back-end programs can be developed independently to implement business logic and interactive effects respectively, and data exchange.

Exploring Go language front-end technology: a new vision for front-end development Exploring Go language front-end technology: a new vision for front-end development Mar 28, 2024 pm 01:06 PM

As a fast and efficient programming language, Go language is widely popular in the field of back-end development. However, few people associate Go language with front-end development. In fact, using Go language for front-end development can not only improve efficiency, but also bring new horizons to developers. This article will explore the possibility of using the Go language for front-end development and provide specific code examples to help readers better understand this area. In traditional front-end development, JavaScript, HTML, and CSS are often used to build user interfaces

Django: A magical framework that can handle both front-end and back-end development! Django: A magical framework that can handle both front-end and back-end development! Jan 19, 2024 am 08:52 AM

Django: A magical framework that can handle both front-end and back-end development! Django is an efficient and scalable web application framework. It is able to support multiple web development models, including MVC and MTV, and can easily develop high-quality web applications. Django not only supports back-end development, but can also quickly build front-end interfaces and achieve flexible view display through template language. Django combines front-end development and back-end development into a seamless integration, so developers don’t have to specialize in learning

See all articles