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 of JavaScript ES12

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article is to share with you about the new features of JavaScript ES12, the editor thinks it is very practical, so I share it with you to learn. I hope you can get something after reading this article.

Every year, JavaScript updates and adds new features and new standards, ES2020 released this year, and ES2020 (ES12) is expected to be released next year, that is, mid-2021. Every year, the new features go through four stages, and the fourth stage is the last stage. What this article will introduce is the relevant new features in proposal 4, which means that these new features will appear in the next version to a large extent.

Features are preemptive:

New replaceAll for String.prototype.replaceAll

Promise.any

WeakRefs

Logical operators and assignment expressions

Numeric separator

ReplaceAll

When you see the word replaceAll, it's easier to associate it with replace. In JavaScript, the replace method can only replace the first instance character matched in the replacement string, but not global multinomial matching. The only way is to match and replace the relevant rules through regular expressions.

On the other hand, replaceAll returns a brand new string, and all characters that match the matching rules will be replaced, which can be strings or regular expressions.

Let string ='I like front end, I like front end male shrimp rice'/ / use replace let replaceStr = string.replace ('like','love') console.log (replaceStr) / /' I love front end, I like front end male shrimp rice'/ / replace use regular matching all console.log (string.replace (/ like/g,'love')) / /'I love front end, I love front end male shrimp rice'/ / use replaceAll let replaceAllStr = string.replaceAll ('like') 'love') console.log (replaceAllStr) / /' I love front end, I love front end male shrimp rice'

It should be noted that when replaceAll uses regular expressions, replaceAll () throws an exception if it does not match globally (/ g).

Let string ='I like front end, I like front end male shrimp rice 'console.log (string.replaceAll (/ like/,'love')) / / TypeError

Promise.any

When any promise in the Promise list succeeds, resolve returns the result status of the first resolve. If all promise are reject, an exception is thrown to indicate that all requests have failed.

Promise.any ([new Promise ((resolve, reject) = > setTimeout (reject, 500,'Oh, I was rejected')), new Promise ((resolve, reject) = > setTimeout (resolve, 1000,'Oh, she accepted me')), new Promise ((resolve, reject) = > setTimeout (resolve, 2000, 'oops) (value = > console.log (`output result: ${value} `)) .catch (err = > console.log (err)) / / output / / output result: oops, she accepted me

Let's take a look at another situation.

Promise.any ([Promise.reject ('Error 1'), Promise.reject ('Error 2'), Promise.reject (' Error 3')] .then (value = > console.log (`request result: ${value} `)) .catch (err = > console.log (err)) / / output AggregateError: All promises were rejected

Promise.any is easy to be confused with Promise.race. It is important to distinguish between Promise.race. Once a promise triggers resolve or reject, it returns the status result directly, regardless of its success or failure.

WeakRefs

Use WeakRefs's Class class to create a weak reference to an object (a weak reference to an object means that the recycling behavior of GC is not prevented when the object should be recycled by GC)

When we create a variable through (const, let, var), the garbage collector GC will never delete the variable from memory, as long as its reference is still accessible. The WeakRef object contains weak references to the object. A weak reference to an object does not prevent the garbage collector GC from restoring a reference to the object, and GC can delete it at any time.

WeakRefs is useful in many cases, such as using Map objects to implement key-value caching that requires a lot of memory, in which case the most convenient thing is to release the memory occupied by key-value pairs as soon as possible.

Currently, you can use WeakRefs through WeakMap () or WeakSet ()

Take a chestnut.

I want to track the number of times a particular object calls a particular method, and prompt for more than 1000

Let map = new Map () function doSomething (obj) {...} function useObject (obj) {doSomething (obj) let called = map.get (obj) | | 0 called + + if (called > 1000) {console.log ('current calls have exceeded 1000, over')} map.set (obj, called)}

Although our function can be implemented as above, a memory overflow occurs because every object passed to the doSomething function is permanently stored in map and will not be recycled by GC, so we can use WeakMap

Let wmap = new WeakMap () function doSomething (obj) {...} function useObject (obj) {doSomething (obj) let called = wmap.get (obj) | | 0 called + + if (called > 1000) {console.log ('current calls have exceeded 1000, over')} wmap.set (obj, called)}

Because they are weak references, the key-value pairs of WeakMap and WeakSet cannot be enumerated.

WeakSet is similar to WeakMap, but each object can only appear once per object in WeakSet, and all objects in WeakSet are unique.

Let ws = new WeakSet () let foo = {} let bar = {} ws.add (foo) ws.add (bar) ws.has (foo) / / true ws.has (bar) / / true ws.delete (foo) / / Delete foo object ws.has (foo) / / false deleted ws.has (bar) / / still exists

There are two differences between WeakSet and Set.

WeakSet can only be a collection of objects, not any type of value

WeakSet weak references. Object references in the collection are weak references. If there are no other references to WeakSet objects, they will be recycled by GC.

Finally, the WeakRef instance has a method deref that returns the referenced original object and undefined if the original object is recycled

Const cache = new Map (); const setValue = (key, obj) = > {cache.set (key, new WeakRef (obj));}; const getValue = (key) = > {const ref = cache.get (key); if (ref) {return ref.deref ();}}; const fibonacciCached = (number) = > {const cached = getValue (number); if (cached) return cached; const sum = calculateFibonacci (number); setValue (number, sum) Return sum;}

This may not be a good idea for caching remote data, because remote data may be unpredictably deleted from memory. In this case, it is best to use a cache such as LRU.

Logical operators and assignment expressions

Logical operators and assignment expressions, the new features combine the logical operators (&, | |,?) and assignment expressions, while the compound assignment operators that already exist in JavaScript are:

Operation operator: + =-= * / =% = * * =

Bit operator: & = ^ = | =

Bitwise operator: = > =

The existing operators can be understood in this way.

Expression: an op= b

Equivalent to: a = an op b

Logical operators work differently from other compound assignment operators

Expression: an op= b

Equivalent to: a = an op (a = b)

A | | = b / / equivalent to aa = a | (a = b) a & & = b / / equivalent to aa = a & & (a = b) a?? = b / / equivalent to aa = a? (a = b)

Why is it no longer the same as the previous formula a = an op b, but a = an op (a = b). Because the latter evaluates the assignment only if and only if the value of an is false, and the assignment is performed only when necessary, while the expression of the former always performs the assignment

? = can be used to supplement / initialize missing attributes

Const pages = [{title:' main venue', path:'/'}, {path:'/other'},...] For (const page of pages) {page.title?? = 'default title'} console.table (pages) / / (index) title path / / 0 "main venue" / "/ / 1" default title "/ other"

Summary:

& & =: assign the RHS variable to LHS when the LHS value exists

| | =: assign the RHS variable to LHS when the LHS value does not exist |

=: when the LHS value is null or undefined, assign the RHS variable to LHS

Numeric separator

Numeric separator, which creates a visual separator between numbers and splits them with an underscore to make them more readable

Const money = 1,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000

The new feature also supports the use of octal numbers

Const number = 0o123_456 / / is equivalent to const number = 0o123456

This new feature makes it easy to read data and makes it easier for us "beating workers" to identify "assets," but then again, the editor's assets don't seem to deserve to use this feature. Hit the point!

Phase 4, which introduces all the new features this time, means that stage 3 will not be introduced in the next release, because it is uncertain whether it will appear in the next release.

These are the new features of JavaScript ES12, and the editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.

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