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.
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!

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

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.


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

Atom editor mac version download
The most popular open source editor

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

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

Dreamweaver CS6
Visual web development tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),