This is the 10th day of my participation in the genwen Challenge

Learning about the new ES features is certainly a must, and the currently released features that have been added to the Google Chrome V8 engine will be studied in this article

1 String.prototype.replaceAll

We all know the string.prototype.replace () method to replace strings

'betterman'.replace('e'.'1111')
// "b1111tterman"

Copy the code

In the string.prototype.replace () method, when the first argument is a String type, only the first matching String is replaced; if we want to replace all, we need to use the re match to

'betterman'.replace(/e/g.'1111')
// "b1111tt111rman"

Copy the code

The new feature eliminates the need for regex

The replaceAll() method returns a new string, all parts of which meet pattern are replaced by replacement. Pattern can be a string or a RegExp, replacement can be a string or a function that is called each time a match is made.

'betterman'.replaceAll('e'.'1111')
'betterman'.replaceAll(/e/g.'1111')
// "b1111tt111rman"

Copy the code

Note: The first argument can be a string or a RegExp, and when using a regex, you must set the global (” G “) flag

2 Logical assignment operator

Logical assignment operators are a combination of logical operators and assignment expressions

  • | | =

The right-hand assignment is performed when the left-hand variable returns false

    // The original way of writing
    a || (a = b);


    if(! a) { a = b; }// Can be written as
    a ||= b;
   

Copy the code
  • &&= Perform the right-hand assignment when the left-hand return value is true
    // The original way of writing
    a && (a = b);

    if (a) {
        a = b;
    }

    // Can be written as
    a &&= b;

Copy the code
  • ?? =

    Entered in ES2020??(void merge operator) the concept of an expression if the expression is in?? The left-hand operator of is evaluated asUndefined or null, returns the default value on the right.

This operator assigns the right variable to the left only if the left variable is undefined or null

    a ?? (a = b);
    if (a === null || a === undefined) {
        a = b;
    }

    // Can be written asa ?? = b;Copy the code

3 Promise.any

The promise.any method is similar to promise.race. Whenever a Promise in a given iteration succeeds, the value of the first Promise is taken as its return value, Race differs from promise.race in that it waits until all promises have failed before returning the failed value:


const myFetch = url= > setTimeout(() = > fetch(url), Math.floor(Math.random() * 3000));
const promises = [
  myFetch('/endpoint-1'),
  myFetch('/endpoint-2'),
  myFetch('/endpoint-3')];// Use.then.catch
Promise.any(promises) // Any promise will succeed.
       .then(console.log) / / such as' 3 '
       .catch(console.error); // All the promises failed
/ / use the async - await
try {
  const first = await Promise.any(promises); // Any promise returns successfully.
 console.log(first);
}catch (error) { // All the promises failed
  console.log(error);
}


Copy the code

4 Digit separator

In the calendar life, we are used to divide the number to be identified. In the code, we divide the number when the number value is large, which can improve the readability of the number

// 8888888888 is not recognizable
const count1 = 8888888888;

// 8_888_888_888 is intuitive
const count2 = 8 _888_888_888;

console.log(count1 === count2); // true


Copy the code

5 WeakRef

A WeakRef object allows you to retain a weak reference to another object without preventing the weakly referenced object from being collected by GC(garbage). A WeakRef object contains a weak reference to the object, which is called the target or referent of the WeakRef 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. In contrast, a normal reference (strong by default) keeps its corresponding object in memory. Only if the object does not have any strong references does the JavaScript engine GC destroy the object and reclaim the memory occupied by the object. If that happens, then you can’t get the object through any weak references.

const ref = new WeakRef({ name: 'better' });
let obj = ref.deref();
if (obj) {
  console.log(obj.name); // better
}


Copy the code

MDN says why avoid it

Proper use of WeakRef objects requires careful consideration and is best avoided. It is also important to avoid relying on any particular behavior that is not guaranteed by the specification. When, how, and if garbage collection occurs depends on the implementation of any given JavaScript engine. GC behavior in one JavaScript engine can be very different in another JavaScript engine, or even in the same type of engine, different versions of GC behavior can be very different. GC is still a challenge for JavaScript engine implementers to continually improve and improve their solutions.

6 Intl.ListFormat

Intl.ListFormat is a language-specific list formatting constructor. The first argument is a locale, and the second argument is an option object — containing both the style and type attributes.

  • Type Message output format. Optional values are “conjunction” that is used instead of A list of “and” relationships (the default, for example, A, B, and C), or “disjunction” that is used instead of A list of “or” relationships (for example: A, B, or C), and “unit” instead of A list of values with units of measure (e.g., 5 pounds, 12 ounces).
  • Style Specifies the length of the message to be formatted. The value can be long (default value, for example, A, B, and C), short, or narrow (for example, A, B, C). When the style value is narrow, the value of the type attribute can only be unit.
const arr = ['Pen'.'Pencil'.'Paper']
 
let obj = new Intl.ListFormat('en', { style: 'short'.type: 'conjunction' })
console.log(obj.format(arr)) 
 
/ * * * * o * * * * /
// Pen, Pencil, & Paper
 
 
obj = new Intl.ListFormat('en', { style: 'long'.type: 'conjunction' })
console.log(obj.format(arr)) 
 
/ * * * * o * * * * /
// Pen, Pencil, and Paper
 
 
obj = new Intl.ListFormat('en', { style: 'narrow'.type: 'conjunction' })
console.log(obj.format(arr)) 
 
/ * * * * o * * * * /
// Pen, Pencil, Paper
 
 
// Pass in the Italian logo
obj = new Intl.ListFormat('it', { style: 'short'.type: 'conjunction' })
console.log(obj.format(arr)) 
 
/ * * * * o * * * * /
// Pen, Pencil e Paper
 
 
// Pass in the German flag
obj = new Intl.ListFormat('de', { style: 'long'.type: 'conjunction' })
console.log(obj.format(arr)) 
 
/ * * * * o * * * * /
// Pen, Pencil und Paper

Copy the code

7 Intl.DateTimeFormat dateStyle and timeStyle options

The Intl.DateTimeFormat object is a constructor that supports language-sensitive date and time formatting. The proposed dateStyle and timeStyle options can be used to get a locale-specific date and time of a given length.

// Short format time
let o = new Intl.DateTimeFormat('en' , { timeStyle: 'short' })
console.log(o.format(Date.now()))
// 11:27 PM
 
 
// Medium format time
o = new Intl.DateTimeFormat('en' , { timeStyle: 'medium'})
console.log(o.format(Date.now()))
// 11:27:57 PM
 
 
// Long format time
o = new Intl.DateTimeFormat('en' , { timeStyle: 'long' })
console.log(o.format(Date.now()))
// 11:27:57 PM GMT+11
 
 
// Short format date
o = new Intl.DateTimeFormat('en' , { dateStyle: 'short'})
console.log(o.format(Date.now()))
/ / 10/6/20
 
 
// Medium format date
o = new Intl.DateTimeFormat('en' , { dateStyle: 'medium'})
console.log(o.format(Date.now()))
// Oct 6, 2020
 
 
// Long format date
o = new Intl.DateTimeFormat('en' , { dateStyle: 'long'})
console.log(o.format(Date.now()))
// October 6, 2020

Copy the code

Refer to the article

  • Exciting features in JavaScript ES2021
  • MDN document
  • The ES2021 brings new features