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!

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.


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

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Chinese version
Chinese version, very easy to use

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Zend Studio 13.0.1
Powerful PHP integrated development environment

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