Home > Web Front-end > JS Tutorial > body text

Share 8 useful features worth collecting in ES2019

青灯夜游
Release: 2021-04-23 19:39:27
forward
1411 people have browsed it

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!

Related labels:
source:segmentfault.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!