5 new features of ES10
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!

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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











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.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.
