Home>Article>Web Front-end> 5 new features of ES10

5 new features of ES10

尚
forward
2020-06-15 17:11:24 2508browse

This year, ECMAScript 2019 (ES2019 for short) will be released. New features include Object.fromEntries(), trimStart(), trimEnd(), flat(), flatMap(), description attribute of symbol objects, optional catch binding, etc.

5 new features of ES10

1、Object.fromEntries()

In JavaScript, convert data from one format to another Very common. To facilitate converting objects into arrays, ES2017 introduced the Object.entrie() method. This method takes an object as a parameter and returns an array of the object's own enumerable string-keyed property pairs in the form [key, value]. For example:

const obj = {one: 1, two: 2, three: 3}; console.log(Object.entries(obj)); // => [["one", 1], ["two", 2], ["three", 3]]

But what if we want to do the opposite and convert the list of key-value pairs into an object? Some programming languages, such as Python, provide the dict() function for this purpose. There is also the _.fromPairs function in Underscore.js and Lodash.

ES2019 introduced the Object.fromEntries() method to bring similar functionality to JavaScript. This static method allows you to easily convert a list of key-value pairs into an object:

const myArray = [['one', 1], ['two', 2], ['three', 3]]; const obj = Object.fromEntries(myArray); console.log(obj); // => {one: 1, two: 2, three: 3}

As you can see, Object.fromEntries() does exactly the opposite of Object.entries(). Although it was previously possible to implement the same functionality of Object.fromEntries(), the way it was implemented was somewhat complicated:

const myArray = [['one', 1], ['two', 2], ['three', 3]]; const Array.from(myArray).reduce((acc, [key, val]) => Object.assign(acc, {[key]: val}), {}) console.log(obj); // => {one: 1, two: 2, three: 3}

Remember that the argument passed to Object.fromEntries() can be any object that implements the iterable protocol, As long as it returns a two-element, array-like object.

For example, in the following code, Object.fromEntries() takes a Map object as a parameter and creates a new object whose keys and corresponding values are given by the pairs in the Map:

const map = new Map(); map.set('one', 1); map.set('two', 2); const obj = Object.fromEntries(map); console.log(obj); // => {one: 1, two: 2}

The Object.fromEntries() method is also very useful for converting objects, consider the following code:

const obj = {a: 4, b: 9, c: 16}; // 将对象转换为数组 const arr = Object.entries(obj); // 计算数字的平方根 const map = arr.map(([key, val]) => [key, Math.sqrt(val)]); // 将数组转换回对象 const obj2 = Object.fromEntries(map); console.log(obj2); // => {a: 2, b: 3, c: 4}

The above code converts the value in the object to its square root. To do this, it first converts the object to an array, then uses the map() method to get the square root of the values in the array. The result is an array that can be converted back to the object.

Another case of using Object.fromEntries() is to handle the query string of the URL, as shown in this example

const paramsString = 'param1=foo¶m2=baz'; const searchParams = new URLSearchParams(paramsString); Object.fromEntries(searchParams); // => {param1: "foo", param2: "baz"}

In this code, the query string will be passed to URLSearchParams() Constructor. The return value (i.e. the URLSearchParams object instance) is then passed to the Object.fromEntries() method, and the result is an object containing each parameter as a property.

The Object.fromEntries() method is currently a stage 4 proposal, which means it is ready for inclusion in the ES2019 standard.

2. trimStart() and trimEnd()

The trimStart() and trimEnd() methods are implemented the same as trimLeft() and trimRight(). These methods are currently in phase 4 and will be added to the specification to be consistent with padStart() and padEnd(), take a look at some examples:

const str = " string "; // es2019 console.log(str.trimStart()); // => "string " console.log(str.trimEnd()); // => " string" // 相同结果 console.log(str.trimLeft()); // => "string " console.log(str.trimRight()); // => " string"

For web compatibility, trimLeft() and trimRight( ) will remain as aliases for trimStart() and trimEnd() .

3. flat() and flatMap()

The flat() method can flatten a multi-dimensional array into a one-dimensional array

const arr = ['a', 'b', ['c', 'd']]; const flattened = arr.flat(); console.log(flattened); // => ["a", "b", "c", "d"]

Previously, we Often use reduce() or concat() to flatten multi-dimensional arrays:

const arr = ['a', 'b', ['c', 'd']]; const flattend = [].concat.apply([], arr); // or // const flattened = [].concat(...arr); console.log(flattened); // => ["a", "b", "c", "d"]

Note that if there are null values in the provided array, they will be discarded:

const arr = ['a', , , 'b', ['c', 'd']]; const flattened = arr.flat(); console.log(flattened); // => ["a", "b", "c", "d"]

flat() Also Accepts an optional parameter that specifies the number of levels by which the nested array should be flattened. If no arguments are provided, the default value of 1 will be used:

const arr = [10, [20, [30]]]; console.log(arr.flat()); // => [10, 20, [30]] console.log(arr.flat(1)); // => [10, 20, [30]] console.log(arr.flat(2)); // => [10, 20, 30]

flatMap() method combines map() and flat() into a single method. It first creates a new array using the return value of the provided function and then concatenates all subarray elements of that array. Here's an example:

const arr = [4.25, 19.99, 25.5]; console.log(arr.map(value => [Math.round(value)])); // => [[4], [20], [26]] console.log(arr.flatMap(value => [Math.round(value)])); // => [4, 20, 26]

The array will be flattened to a depth level of 1. If you want to remove items from the result, just return an empty array:

const arr = [[7.1], [8.1], [9.1], [10.1], [11.1]]; // do not include items bigger than 9 arr.flatMap(value => { if (value >= 10) { return []; } else { return Math.round(value); } }); // returns: // => [7, 8, 9]

Except for the current element being processed In addition, the callback function will receive the index of the element and a reference to the array itself. The flat() and flatMap() methods are currently in stage 4.

4. Description attribute of Symbol object

When creating a Symbol, you can add a description (description) to it for debugging purposes. Sometimes it is useful to have direct access to the description in the code.

ES2019 adds a read-only attribute description to the Symbol object, which returns a string containing the Symbol description.

let sym = Symbol('foo'); console.log(sym.description); // => foo sym = Symbol(); console.log(sym.description); // => undefined // create a global symbol sym = Symbol.for('bar'); console.log(sym.description); // => bar

5. Optional catch

The catch in the try catch statement is sometimes useless. Think about the following code:

try { // 使用浏览器可能尚未实现的功能 } catch (unused) { // 这里回调函数中已经帮我们处理好的错误 }

This code The information in the catch callback is not useful. But it is written this way to avoid SyntaxError errors. ES2019 can omit the brackets around catch:

try { // ... } catch { // .... }

Also: ES2020’s String.prototype.matchAll

matchAll() method is an ES2020 phase 4 proposal, which returns all matches for regular expressions ( Iterator object including capturing groups).

To be consistent with the match() method, TC39 chose "matchAll" instead of other suggested names, such as "matches" or Ruby's "scan". Consider a simple example:

const re = /(Dr\. )\w+/g; const str = 'Dr. Smith and Dr. Anderson'; const matches = str.matchAll(re); for (const match of matches) { console.log(match); } // logs: // => ["Dr. Smith", "Dr. ", index: 0, input: "Dr. Smith and Dr. Anderson", groups: undefined] // => ["Dr. Anderson", "Dr. ", index: 14, input: "Dr. Smith and Dr. Anderson", groups: undefined]

The capturing group in this regular expression matches the characters "Dr" followed by a dot and a space. \w matches any word character one or more times. And the g flag instructs the engine to search for patterns throughout the string.

Previously, one had to use the exec() method in a loop to achieve the same result, which was not very efficient:

const re = /(Dr\.) \w+/g; const str = 'Dr. Smith and Dr. Anderson'; let matches; while ((matches = re.exec(str)) !== null) { console.log(matches); } // logs: // => ["Dr. Smith", "Dr.", index: 0, input: "Dr. Smith and Dr. Anderson", groups: undefined] // => ["Dr. Anderson", "Dr.", index: 14, input: "Dr. Smith and Dr. Anderson", groups: undefined]

重要的是要注意尽管match() 方法可以与全局标志g一起使用来访问所有匹配,但它不提供匹配的捕获组或索引位置。 比较以下代码:

const re = /page (\d+)/g; const str = 'page 2 and page 10'; console.log(str.match(re)); // => ["page 2", "page 10"] console.log(...str.matchAll(re)); // => ["page 2", "2", index: 0, input: "page 2 and page 10", groups: undefined] // => ["page 10", "10", index: 11, input: "page 2 and page 10", groups: undefined]

总结

在这篇文章中,我们仔细研究了 ES2019 中引入的几个关键特性,包括Object.fromEntries(),trimStart(), trimEnd(), flat(), flatMap(),symbol 对象的description 属性以及可选的catch 。

更多相关知识请关注JavaScript视频教程栏目

The above is the detailed content of 5 new features of ES10. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:javanx.cn. If there is any infringement, please contact admin@php.cn delete