Home Web Front-end JS Tutorial 5 new features of ES10

5 new features of ES10

Jun 15, 2020 pm 05:11 PM

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

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

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

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

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

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&param2=baz';
const searchParams = new URLSearchParams(paramsString);

Object.fromEntries(searchParams);    // => {param1: "foo", param2: "baz"}
Copy after login

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"
Copy after login

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

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

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

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

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

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

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

5. Optional catch

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

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

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

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

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

重要的是要注意尽管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]
Copy after login

总结

在这篇文章中,我们仔细研究了 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 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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

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)

How do I create and publish my own JavaScript libraries? How do I create and publish my own JavaScript libraries? Mar 18, 2025 pm 03:12 PM

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

How do I optimize JavaScript code for performance in the browser? How do I optimize JavaScript code for performance in the browser? Mar 18, 2025 pm 03:14 PM

The article discusses strategies for optimizing JavaScript performance in browsers, focusing on reducing execution time and minimizing impact on page load speed.

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

How do I debug JavaScript code effectively using browser developer tools? How do I debug JavaScript code effectively using browser developer tools? Mar 18, 2025 pm 03:16 PM

The article discusses effective JavaScript debugging using browser developer tools, focusing on setting breakpoints, using the console, and analyzing performance.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How do I use source maps to debug minified JavaScript code? How do I use source maps to debug minified JavaScript code? Mar 18, 2025 pm 03:17 PM

The article explains how to use source maps to debug minified JavaScript by mapping it back to the original code. It discusses enabling source maps, setting breakpoints, and using tools like Chrome DevTools and Webpack.

Getting Started With Chart.js: Pie, Doughnut, and Bubble Charts Getting Started With Chart.js: Pie, Doughnut, and Bubble Charts Mar 15, 2025 am 09:19 AM

This tutorial will explain how to create pie, ring, and bubble charts using Chart.js. Previously, we have learned four chart types of Chart.js: line chart and bar chart (tutorial 2), as well as radar chart and polar region chart (tutorial 3). Create pie and ring charts Pie charts and ring charts are ideal for showing the proportions of a whole that is divided into different parts. For example, a pie chart can be used to show the percentage of male lions, female lions and young lions in a safari, or the percentage of votes that different candidates receive in the election. Pie charts are only suitable for comparing single parameters or datasets. It should be noted that the pie chart cannot draw entities with zero value because the angle of the fan in the pie chart depends on the numerical size of the data point. This means any entity with zero proportion

TypeScript for Beginners, Part 2: Basic Data Types TypeScript for Beginners, Part 2: Basic Data Types Mar 19, 2025 am 09:10 AM

Once you have mastered the entry-level TypeScript tutorial, you should be able to write your own code in an IDE that supports TypeScript and compile it into JavaScript. This tutorial will dive into various data types in TypeScript. JavaScript has seven data types: Null, Undefined, Boolean, Number, String, Symbol (introduced by ES6) and Object. TypeScript defines more types on this basis, and this tutorial will cover all of them in detail. Null data type Like JavaScript, null in TypeScript

See all articles