preface
Word limit ES6 to ES10 See ECMAScript2016 to 2019
ECMAScript2020(ES11)
String extensions
- String.prototype.matchAll()
The matchAll() method returns an iterator containing all matched regular expressions and grouped capture results
const str = ` < HTML > < body > < div > the first div < / div > < p > this is a p < / p > < span > span < / span > < div > second div < / div > < body > < / HTML > `
Copy the code
Find all the div elements.
function selectDiv(regExp, str) {
let matches = []
for (let match of str.matchAll(regExp)) {
matches.push(match[1])}return matches
}
const res = selectDiv(regExp, str)
console.log(res)
Copy the code
Dynamic Import
The On-demand import proposal has been around for a few years now, and is finally making it into the FORMAL ES specification. “On demand” is more appropriate. Modern front-end packaging resources are increasing, packaging into several M JS resources has become a normal, but often front-end application initialization does not need to load the full logical resources, in order to speed up the first screen rendering, many times are loaded on demand, such as lazy loading images. The on-demand logic resources are loaded in an event callback.
There is a button on the page that you click to load the Ajax module.
const oBtn = document.querySelector('#btn')
oBtn.addEventListener('click'.() = > {
import('./ajax').then(mod= > {
// console.log(mod)
mod.default('static/a.json'.res= > {
console.log(res)
})
})
})
Copy the code
Of course, WebPack now has good support for this feature.
BigInt
Added a new primitive data type in ES10: BigInt, which represents an integer of arbitrary precision, can represent extremely long data, and can exceed 2 to the power of 53.
The Js Number type can only safely represent values from -(2^53-1) to 2^53-1
console.log(2支那53) // Es7 power operator
console.log(Number.MAX_SAFE_INTEGER) // The maximum value is -1
Copy the code
There are two ways to use BigInt:
- Method 1: Add n after a number
const bigInt = 9007199254740993n
console.log(bigInt)
console.log(typeof bigInt) // bigint
console.log(1n= =1) // true
console.log(1n= = =1) // false
Copy the code
- Method 2: Use BigInt
const bigIntNum = BigInt(9007199254740993n)
console.log(bigIntNum)
Copy the code
Promise.allSettled()
With the new ES feature, we all know promise.all () has the ability to execute asynchronous tasks concurrently. The biggest problem with this is that if one of the tasks fails, all the tasks hang, and the Promise goes straight into reject. While Promise.allSettled returns a Promise settled after all given promises have been settled or rejected, with an array of objects, each representing the corresponding Promise result.
Promise.allSettled([
Promise.reject({
code: 500.msg: 'Service exception'
}),
Promise.resolve({
code: 200.data: ['1'.'2'.'3']}),Promise.resolve({
code: 200.data: ['4'.'5'.'6']
})
]).then(res= > {
console.log(res)
// console.log(' success ')
const data = res.filter(item= > item.status === 'fulfilled')
console.log(data)
}).catch(err= > {
console.log(err)
console.log('failure')})Copy the code
globalThis
Javascript has different ways of getting global objects in different environments:
- Node passes global
- On the Web through Windows, self, etc.
Self: When you open any web page, the browser first creates a window. This window is a window object, which is also the global environment object and global scope object that js runs on. Self refers to the window itself, which returns the same object as the window object. Because of this, common methods and functions of the window object can replace the window with self.
GlobalThis provides a standard way to get globalThis objects (that is, global objects themselves) in different environments. Unlike properties like Window or self, it ensures that it works in all environments with and without Windows. So, you can safely use globalThis without worrying about its runtime environment. For memorization purposes, you just need to remember that this in the global scope is globalThis.
console.log(globalThis)
Copy the code
Optional chain chaining
This allows us to query multi-tiered objects without the need for redundant pre-validation.
const user = {
address: {
street: 'xx street'.getNum() {
return '80'}}}Copy the code
Uncaught TypeError: Cannot read Property Uncaught TypeError: Cannot read property… This kind of error, this is very likely to kill your entire application.
const street = user && user.address && user.address.street
const num = user && user.address && user.address.getNum && user.address.getNum()
console.log(street, num)
Copy the code
With Optional Chaining, the above code becomes
conststreet2 = user? .address? .streetconstnum2 = user? .address? .getNum? . ()console.log(street2, num2)
Copy the code
Optional chain? Indicates that if the expression to the left of the question mark has a value, the field following the question mark continues to be queried. As can be seen from the above, using the optional chain can greatly simplify the similar tedious pre-check operation, and it is safer.
Coalescing Operator (Nullish coalescing Operator)
Null-value merge operator (??) Is a logical operator. When the left-hand operand is null or undefined, it returns the right-hand operand. Otherwise return the left-hand operand.
When we query for an attribute, we often encounter that a default value is set if the attribute is not available.
const b = 0 // or null undefined false
const a = b || 5
console.log(a)
Copy the code
Null-value merge operator?? We only set the default value if the first item is null or undefined
// false 0 is invalid
const a = b ?? 123
console.log(a)
Copy the code
ECMAScript2021(ES12)
replaceAll
Returns a brand new string, with all characters matching the rules replaced
const str = 'hello world';
str.replaceAll('l'.' '); // "heo word"
Copy the code
Promise.any
Promise.any() receives a Promise iterable and returns the Promise that succeeded as soon as one of the promises succeeds. If none of the iterable promises succeeds (i.e. all promises fail/reject), return a failed promise.
const promise1 = new Promise((resolve, reject) = > reject('I'm Promise_1 to fail'));
const promise2 = new Promise((resolve, reject) = > reject('I'm Promise_2 to fail'));
const promiseList = [promise1, promise2];
Promise.any(promiseList)
.then(values= >{
console.log(values);
})
.catch(e= >{
console.log(e);
});
Copy the code
WeakRefs
WeakRefs Class creates a weak reference to an object (a weak reference to an object means that it does not prevent the GC from collecting when the object should be collected by the GC)
When we create a variable through (const, let, var), the garbage collector GC will never remove the variable from memory as long as its reference remains accessible. A WeakRef object contains weak references to an object. A weak reference to an object does not prevent the garbage collector’S GC from recovering the reference to the object, so the GC can delete it at any time.
WeakRefs can be useful in many situations, such as using Map objects to implement key and value caches with a lot of memory, in which case it is most convenient to release the memory occupied by key and value pairs as soon as possible.
Currently, WeakRefs can be used with a WeakMap() or a WeakSet()
I want to keep track of how many times a particular object calls a particular method, and be prompted for more than 1000
let map = new Map(a)function doSomething(obj){... }function useObject(obj){
doSomething(obj)
let called = map.get(obj) || 0
called ++
if(called>1000) {console.log('It's been called more than 1000 times, over')
}
map.set(obj, called)
}
Copy the code
Although the above can achieve our function, memory overflow will occur because every object passed to the doSomething function is permanently stored in map and will not be collected by GC, so we can use WeakMap
let wmap = new WeakMap(a)function doSomething(obj){... }function useObject(obj){
doSomething(obj)
let called = wmap.get(obj) || 0
called ++
if(called>1000) {console.log('It's been called more than 1000 times, over')
}
wmap.set(obj, called)
}
Copy the code
Logical operators and assignment expressions
Operators and assignment expression, new features combined with logical operators, &&, | |,??) And assignment expressions. JavaScript already has the following compound assignment operators
a ||= b
/ / equivalent to the
a = a || (a = b)
a &&= b
/ / equivalent to thea = a && (a = b) a ?? = b/ / equivalent to the
a = a ?? (a = b)
Copy the code
Numeric separator
Number delimiters, you can create visual separators between numbers, which are separated by underscores to make numbers more readable
const money = 1 _000_000_000;
/ / equivalent to the
const money = 1000000000;
1 _000_000_000= = =1000000000; // true
Copy the code
Refer to the article
- New JavaScript ES12 features get a head start
- ES6, ES7, ES8, ES9, ES10, ES11, ES12 new features
- ECMAScript2015 to 2020 Syntax is fully parsed