Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the new features added to ES11

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the relevant knowledge of "what are the new features of ES11". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

ECMAScript 2020 is the 11th edition of the ECMAScript language specification. Since the first edition was published in 1997, ECMAScript has developed into one of the most widely used general programming languages in the world.

ES2020 (ES11) introduces the following new features:

MatchAll method of String

Dynamic import statement import ()

Import.meta

Export * as ns from 'module'

Promise.allSettled

A new data type: BigInt

GlobalThis

Nullish coalescing Operator

Optional Chaining

MatchAll

The matchAll () method returns an iterator that contains the results of all matching regular expressions. Use for...of to traverse or use operators... Array.from converts it to an array.

Const reg = / [0-3] / g; const data = '2020; console.log (data.matchAll (reg)); / / the return value of data.matchAll is an iterator console.log ([... data.matchAll (reg)]) / * 0: ["2", index: 0, input: "2020", groups: undefined] * 1: ["0", index: 1, input: "2020", groups: undefined] * 2: ["2", index: 2, input: "2020", groups: undefined] * 3: ["0", index: 3, input: "2020", groups: undefined] * /

Dynamic import

The module imported by the standard import is static and causes all imported modules to be compiled at load time (unable to compile on demand, slowing down the home page loading speed). In some scenarios, you may want to import modules according to conditions or on demand, and you can use dynamic imports instead of static imports.

Before import (), we had to use require () when we needed to import modules based on conditions.

Such as:

If (XXX) {const menu = require ('. / menu');}

It can now be replaced by:

If (XXX) {const menu = import ('. / menu');}

@ babel/preset-env already includes @ babel/plugin-syntax-dynamic-import, so if you want to use the import () syntax, you just need to configure @ babel/preset-env.

Tip: please abuse dynamic import (only if necessary). Static frameworks can better initialize dependencies and make it easier for static analysis tools and tree shaking to play a role.

In addition, import () returns a promise object. For example:

/ / menu.js export default {menu: 'menu'} / / index.js if (true) {let menu = import ('. / menu'); console.log (menu); / / Promise {menu.then (data = > console.log (data)); / / Module {default: {menu: "menu"}, _ _ esModule: true, Symbol (Symbol.toStringTag): "Module"} else {}

Import.meta

Import.meta returns an object with a url property that returns the url path of the current module, which can only be used within the module.

/ / main.js console.log (import.meta); / / {url: "http://localhost:8080/main.js"} PS: used

Because import.meta must be used within the module, if you do not add type= "module", the console will report an error: Cannot use 'import.meta' outside a module.

At the beginning of the test, I tested in the React project. Only @ babel/preset-env and @ babel/preset-react presets were configured. When using import.meta, the error is as follows:

Install @ open-wc/webpack-import-meta-loader, modify the configuration of webpack, and run normally.

Module: {rules: [{test: /\ .js $/, use: [require.resolve ('@ open-wc/webpack-import-meta-loader'), {loader: 'babel-loader' Options: {presets: ["@ babel/preset-env", "@ babel/preset-react"]} }]}]}

The effect is as follows:

/ / src/index.js import React from 'react'; console.log (import.meta); / / {index.js:38 {url: "http://127.0.0.1:3000/src/index.js"}}

Export * as ns from 'module'

ES2020 added export * as XX from 'module', and import * as XX from' module'

/ / menu.js export * as ns from'. / info'

It can be understood as merging the following two statements into one sentence:

Import * as ns from'. / info'; export {ns}

It is important to note, however, that export * as ns from'. / info' will not actually import the module, so we cannot get the ns in the module (menu.js).

Promise.allSettled

Sometimes Promise.all or Promise.race can't meet our needs. For example, we need to do something when all promise ends, regardless of whether they succeed or fail. Before we had Promise.allSettled, we needed to write our own implementation.

The Promise.allSettled () method returns a promise after all given promise have been fulfilled or rejected, with an array of objects, each representing the corresponding promise result.

Const promise1 = Promise.resolve; const promise2 = new Promise ((resolve, reject) = > setTimeout (reject, 100,' info')); const promise3 = new Promise ((resolve, reject) = > setTimeout (resolve, 200,' name') Promise.allSettled ([promise1, promise2, promise3]). Then ((results) = > console.log (result)); / * [{status: 'fulfilled', value: 100}, {status:' rejected', reason: 'info'}, {status:' fulfilled', value: 'name'}] * /

As you can see, the result of the success of Promise.allSettled () is an array, each item of the array is an object, each object has a status property with a value of fulfilled or rejected, if the value of status is fulfilled, then the object also has a value property whose property value is the result of the success of the corresponding promise; if the value of status is rejected, then the object has a reason property whose attribute value is the reason for the corresponding promise failure.

BigInt

BigInt is a numeric type of data that can represent integers in any precision format. Before that, the maximum number of security in JS was 9009199254740991, or 2 ^ 53-1, which can be viewed by entering Number.MAX_SAFE_INTEGER in the console. Beyond this value, JS has no way to express it accurately. In addition, a value greater than or equal to 2 to the power of 1024, which JS cannot represent, returns Infinity.

BigInt solves these two problems. BigInt is only used to represent integers, there is no limit to the number of digits, any number of integers can be accurately represented. In order to distinguish from the Number type, the data of the BigInt type must be suffixed with n.

/ / when the Number type exceeds 9009199254740991, there is a problem with the calculation result: const num1 = 90091992547409910; console.log (num1 + 1); / / 90091992547409900 / / BigInt calculation results strive for const num2 = 90091992547409910n; console.log (num2 + 1n); / 90091992547409911n / Number type cannot represent the value let num3 = 9999 of the 1024th power greater than 2; for (let I = 0; I < 10; ispeak +) {num3num3 = num3 * num3;} console.log (num3) / / Infinity / / BigInt type can represent any number of integers let num4 = 9999n; for (let I = 0n; I < 10n; iTunes +) {num4num4 = num4 * num4;} console.log (num4); / / A string of super-long numbers, which will not be posted here.

We can also use the BigInt object to initialize the BigInt instance:

Console.log (BigInt (999)); / / 999n Note: no new keyword!

It is important to note that BigInt and Number are two data types, and four operations cannot be performed directly, but comparison operations can be performed.

Console.log (99n = = 99); / / true console.log (99n = 99); / / false console.log (99n + 1); / / TypeError: Cannot mix BigInt and other types, use explicit conversionss

GlobalThis

There is a top-level object in JS, but the top-level object is not uniform in various implementations.

Getting global objects from different JavaScript environments requires different statements. In Web, you can get global objects through window and self, but in Web Workers, only self can. In Node.js, none of them can be obtained, so you must use global.

Before globalThis, let's get the global object like this:

Var getGlobal = function () {if (typeof self! = = 'undefined') {return self;} if (typeof window! = =' undefined') {return window;} if (typeof global! = = 'undefined') {return global;} throw new Error (' unable to locate global object');}

GlobalThis is introduced into ES2020 as the top-level object. In any environment, the top-level object can be easily obtained through globalThis.

Nullish coalescing Operator

ES2020 has added an operator?? When the left Operand is null or undefined, the right Operand is returned, otherwise the left Operand is returned.

Use the | | operator. When the Operand on the left is 0, null, undefined, NaN, false,'', the Operand on the right will be used. If you use | | to set default values for some variables, you may encounter unexpected behavior.

For example:

Const defaultValue = 100; let value = someValue | | defaultValue; / / when someValue is converted to boolean and false, the value of value is defaultValue

When the value of someValue is 0, we actually expect the value of value to be 0, but it is mistakenly assigned to 100.

?? The operator avoids the above problem by returning the right Operand only if the left Operand is null or undefined.

Const defaultValue = 100; let value = someValue | | defaultValue;//someValue is 0 and value is 0.

Optional Chaining

Optional chain operator?. Allows you to read the value of a property deep in the chain of connected objects without explicitly verifying that each reference in the chain is valid. ?. The function of the operator is similar to. Chain operator, the difference is that it does not cause an error when the reference is empty (nullish, that is, null or undefined), and the expression short circuit returns a value of undefined.

For example, we want to access the tortoise of the animal's reptile of the info object. But we are not sure whether animal reptile exists, so we need to write:

Const tortoise = info.animal & & info.animal.reptile & & info.animal.reptile.tortoise

Because null.reptile or undefined.reptile will throw an error: TypeError: Cannot read property 'reptile' of undefined or TypeError: Cannot read property' reptile' of null, to avoid reporting errors, this code will get longer and longer if we need to access deeper attributes.

With the optional chain operator?., we no longer need to verify the value of info.animal before accessing reptile. Similarly, there is no need to verify the value of info.animal.reptile before accessing info.animal.reptile.tortoise.

The above code is simplified to:

Const tortoise = info.animal?.reptile?.tortoise

Before attempting to access info.animal.reptile, JS implicitly checks and determines that the value of info.animal is not null or undefined, and if its value is null or undefined, the expression short-circuit evaluation directly returns undefined.

You can see the optional chain operator?. As with the vacancy merge operator, it is for the values null and undefined.

This is the end of the content of "what are the new features added to ES11". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report