Note: This list only lists the new features that are commonly used in work or that are easy to use. Some of the small problems and special scenarios that may be encountered in the use of these features are for reference only.

A, ES6 (2015).

ES6 references the new features listed in Ruan yifeng, combined with little knowledge at work.

1.1, let const

A declared variable/constant is valid only within the code block in which it is located.

ES6 makes it clear that temporary dead zones and let and const statements do not promote variables. The main purpose of ES6 is to reduce runtime errors and prevent the variable from being used before it is declared, resulting in unexpected behavior.

1.2. Deconstructing assignment

Deconstruction: ES6 syntax for extracting values from arrays and objects and assigning values to variables

  • An array of

Array structure assignment: Make sure the left and right sides have the same structure

let [a, b, c] = [1.2.3]; // We can extract values from arrays and assign values to variables according to their positions
console.log(`a=${a},b=${b},c=${c}`); // a=1,b=2,c=3

let [foo, [[bar], baz]] = [1The [[2].3]].console.log(`foo=${foo},bar=${bar},baz=${baz}`); // foo=1,bar=2,baz=3

let [head, ...tail] = [1.2.3.4];
console.log(head); // head 1
console.log(tail); // tail [2, 3, 4]

let [x = 1, y = x] = [1.2]; // Add a default value to destruct assignment
console.log(`x=${x},y=${y}`); // x=1,y=2
Copy the code
  • object

Object deconstruction assignment: first find the property of the same name, and then assign to the corresponding variable. It is the latter, not the former, that is really assigned.

let { foo: baz } = { foo: "aaa".bar: "bbb" };
baz // "aaa"
foo // error: foo is not defined
Copy the code

Foo matches the pattern baz to which the variable is assigned

  • string

String deconstruction assignment: The string is converted to an array-like object.

const [a, b, c, d, e] = 'hello';
a // "h"
b // "e"
c // "l"
d // "l"
e // "o"
Copy the code

Array-like objects all have a common attribute length:

let {length : len} = 'hello';
len / / 5
Copy the code
  • The numerical

Deconstructive assignment of a value: By default, it is converted to an object and its attributes are taken

let {toString: s} = 123;
s === Number.prototype.toString // true
Copy the code
  • Boolean value

Boolean deconstructive assignment: By default, it is converted to an object and its attributes are taken

let {toString: s} = true;
s === Boolean.prototype.toString // true
Copy the code
  • function

Destruct assignment of function arguments: Destruct assignment of arrays, objects, etc

[[1.2], [3.4]].map(([a, b]) = > a + b); // [3, 7]

function move({x = 0, y = 0} = {}) {
    return [x, y];
}
move({x: 3.y: 8}); / / [3, 8]
move({x: 3}); / / [3, 0]
move({}); / / [0, 0]
move(); / / [0, 0]
Copy the code

1.3. Extend operators

  • The extension operator uses three dots.Function to expand an array or array-like object into a series of comma-separated values
let foo = function(a, b, c) { 
    console.log(a); 
    console.log(b); 
    console.log(c); 
} 
let arr = [1.2.3]; // The traditional way
foo(arr[0], arr[1], arr[2]); // Use the extension operatorfoo(... arr);// 1/2/3

// Array deep copy
let arr2 = arr; 
let arr3 = [...arr]; // Divide the array and assign
console.log(arr === arr2); // true, arr and arR2 refer to the same array
console.log(arr === arr3); // false to indicate that arr3 and arr point to different arrays

// Insert one array into another array literal
let arr4 = [...arr, 4.5.6]; 
console.log(arr4);  // [1, 2, 3, 4, 5, 6] 

// String to array
let str = 'hello'; 
let arr5 = [...str]; 
console.log(arr5); // [ 'h', 'e', 'l', 'l', 'o' ]
Copy the code
  • Map and Set structures, Generator functions
let map = new Map([[1.'one'],
    [2.'two'],
    [3.'three']]); [...map.keys()];/ / [1, 2, 3]

let set = new Set([4.5.6]);
[...set]; / / [4, 5, 6]

let go = function* () {
    yield 1;
    yield 2;
    yield 3;
};
[...go()]; / / [1, 2, 3]
Copy the code

1.4. Rest Parameters

Rest arguments (of the form… Variable name), used to get extra arguments to a function so you don’t need to use the arguments object. The rest argument goes with a variable that puts the extra arguments into an array.

/ / the arguments variables
function sortNumbers() {
  return Array.prototype.slice.call(arguments).sort();
}

/ / rest parameters
const sortNumbers = (. numbers) = > numbers.sort();
Copy the code

Note: the arguments is an Array of class objects, you can use the Array. The prototype. Slice. Call it into an Array.

1.5. Strings

  • Template string

Solve the previous tedious string concatenation method, template string is an enhanced version of the string, the use of backquotes’ identification, can be used to define multi-line string, string embedded variables, etc.

const data = {key: 'key'};

/ / before
console.log(
    'This is a multi-line text string,' +
    'Notice the newline display of the text content. '
);
console.log('This is a string with variables embedded in it.' + ' ' + data.key);

// Template string
console.log('This is a multi-line text string. Note the newline display of the text content. `);
console.log('This is a string in which variables are embedded${data.key}`);
Copy the code

${} = ${}; ${} = ${};

console.log('This is a string in which variables are embedded${data.name}`); // This is a string with undefined embedded in it
Copy the code
  • includes()

Returns true/false to determine whether a character is contained in a string. A second parameter is supported, indicating the location to start the search.

'Hello world'.includes('ll'); // true
'Hello world'.includes('ll'.5); // false
Copy the code
  • startsWith()

Returns true/false to determine if a character is at the head of a string. A second parameter is supported, indicating the location to start the search.

'Hello world'.startsWith('He'); // true
'Hello world'.startsWith('He'.5); // false
Copy the code
  • endsWith()

Returns true/false to determine if a character is at the end of a string. The second parameter is supported, indicating the search for the first n characters.

'Hello world'.endsWith('ld'); // true
'Hello world'.endsWith('ld'.5); // true
Copy the code
  • repeat()

Used to repeat the original string n times, returning a new string.

If it’s a decimal, it’s an integer part if it’s a 0 it’s an empty string if it’s a decimal before 0 to -1 or NaN it’s the same as 0 if it’s any other negative number or Infinity it’s an exception

'na'.repeat(2) // "nana"
'na'.repeat(2.9) // "nana"
'na'.repeat(0) / / ""
'na'.repeat(-0.9) / / ""
'na'.repeat(NaN) / / ""
'na'.repeat(-1); // RangeError
Copy the code
  • matchAll()

Used to return all matches of a regular expression in the current string.

let str = 'aabbcc';
let arr = [...str.matchAll('b')]; // [["b", index: 2, input: "aabbcc", groups: undefined],["b", index: 3, input: "aabbcc", groups: undefined]]
Copy the code
  • String.fromCharCode()

Used to recognize Unicode codes and return the corresponding character, but this method does not recognize characters with code points greater than 0xFFFF.

String.fromCharCode(0x20BB7); / / "ஷ"
Copy the code
  • String.fromCodePoint()

Used to identify characters with Unicode code points greater than 0xFFFF.

String.fromCodePoint(0x20BB7); / / "𠮷"
Copy the code

1.6, numerical

  • Number.isFinite()

Used to determine if the value is finite and not Infinity, returns true/false. Return false for non-numeric arguments.

Number.isFinite(1); // true
Number.isFinite(Infinity); // false
Copy the code
  • Number.isNaN()

Used to determine whether the value is NaN.

Number.isNaN(NaN); // true
Number.isNaN(1); // false
Copy the code
  • Number.parseInt()Number.parseFloat()

To reduce global methods and modularize the language, ES6 ports global parseInt() and parseFloat() onto Number objects.

parseInt('12.34'); / / 12
parseFloat('123.45 #'); / / 123.45

Number.parseInt('12.34'); / / 12
Number.parseFloat('123.45 #'); / / 123.45
Copy the code
  • Number.isInteger()

Checks whether the value is an integer and returns true/false. Return false for non-numeric arguments.

Number.isInteger(25); // true
Number.isInteger(25.0); // true
Copy the code
  • Math.trunc()

In the past, Math has rounded up and rounded down for numeric values, but there is a scenario where positive and negative numbers do not directly satisfy our need to take only the integer part. Math.trunc() removes the decimal part of a number and returns the integer part.

For non-numeric values, the Number is converted internally and NaN is returned when a parameter cannot be converted to a value

Math.trunc(2.9); / / 2
Math.trunc('2.9'); / / 2
Math.trunc(true); / / 1
Math.trunc(NaN); // NaN
Copy the code
  • Math.sign()

Used to determine whether a number is positive, negative, or zero. For non-numeric values, they are converted to numeric values first.

If the argument is positive, return +1 if the argument is negative, return -1 if the argument is 0, return 0 if the argument is -0, return -0 other values, return NaN

1.7, functions,

  • The default value
// let const x and y are declared by default. Let const x and y are declared by default
function setParam(x, y = 1) {
    console.log(x, y);
}
Copy the code

Note: If the input parameter is undefined, the default value is used. If the input parameter is null, the default value cannot be used.

  • Arrow function

The arrow function makes the expression more concise.

// Concise statements can be returned directly
[1.2.3].map(x= > x * x);

// Wrap with parentheses
const getTempItem = id= > ({ tempId: id, name: 'Temp' });
Copy the code

Since it does not have its own this object in scope, it is bound to this in the upper scope at definition time, which means that the this pointer inside the arrow function is fixed.

// ES5
function foo() {
    let _this = this;

    setTimeout(function () {
        console.log('id:', _this.id);
    }, 100);
}

// ES6
function foo() {
    setTimeout(() = > {
        console.log('id:'.this.id);
    }, 100);
}
Copy the code

Note: Even if an arrow function has a nested arrow function, its this points to only one function, the outermost function defined.

function foo() {
    return () = > {
        return () = > {
            return () = > {
                console.log('id:'.this.id);
            };
        };
    };
}

let f = foo.call({id: 1});

let t1 = f.call({id: 2}) () ();// id: 1
let t2 = f().call({id: 3}) ();// id: 1
let t3 = f()().call({id: 4}); // id: 1
Copy the code

1.8, arrays,

  • Array.from()

Array.from is used to convert two types of objects into true arrays: array-like objects and iterable objects (including the new data structures Set and Map in ES6). Extended operators… You can also turn some data structures into arrays.

/ / Set, and the Map
const setArr = new Set([1.2.3.1.2]); // Set(3) {1, 2, 3}
console.log(Array.from(setArr), [...setArr]); / / [1, 2, 3]

/ / the arguments object
function foo() {
    let args = Array.from(arguments);
    console.log(args, [...arguments]);
}
foo('name'.'age'); // ['name', 'age']
Copy the code
  • find,findIndex

Includes three parameters:

Value Current value index Index of the current value ARR Original array

The find method of an array instance, used to find the first array member that matches the criteria. Its argument is a callback function that is executed by all array members until the first member that returns true is found, and then returned. If there is no qualified member, undefined is returned.

[1.4, -5, -2.10].find((n) = > n < 0); / / - 5
Copy the code

The findIndex method on an array instance is used much like the find method, returning the location of the first qualified array member, or -1 if all members fail.

[1.4, -5, -2.10].findIndex((n) = > n > 4); / / 4
[1.4, -5, -2.10].findIndex((n) = > n > 4); // -1
Copy the code

You can take a second argument to bind the this object of the callback function.

The this object in the callback refers to the Person object
function f(v) {
    return v > this.age;
}
const person = {name: 'John'.age: 20};
[10.12.26.15].find(f, person); / / 26
Copy the code

1.9, objects,

  • Element shorthand
function foo(x, y) {
    // return {x: x, y: y};
    return {x, y};
}
Copy the code
  • Attribute traversal

for ... in

for(let key in {name: 'wqjiao'.age: 18{})console.log(key);
}
Copy the code

Keys (obj) -> this method was introduced in ES5

Object.keys({name: 'wqjiao'.age: 18}); // ['name', 'age']
Copy the code

Object.getOwnPropertyNames(obj)

Object.getOwnPropertyNames({name: 'wqjiao'.age: 18[Symbol('height')]: 167}); // ['name', 'age']
Copy the code

Object.getOwnPropertySymbols(obj)

Object.getOwnPropertySymbols({name: 'wqjiao'.age: 18[Symbol('height')]: 167}); // [Symbol(height)]
Copy the code

Reflect.ownKeys(obj)

Reflect.ownKeys({name: 'wqjiao'.age: 18[Symbol('height')]: 167}); // ["name", "age", Symbol(height)]
Copy the code
  • The order in which attributes are traversed

First, all numeric keys are iterated, sorted in ascending order. Next, all the string keys are iterated in ascending order by the time they were added. Finally, all Symbol keys are iterated in ascending order of time they were added.

  • Object.is()

Used to compare whether two values are strictly equal, basically the same behavior as ===, but the same for NaN.

Object.is('foo'.'foo'); // true
Object.is({}, {}); // false
Object.is(+0, -0); // false
Object.is(NaN.NaN); // true
Copy the code

1.10, Symbol

Represents a unique value that belongs to one of the original data types

Undefined null Boolean String Number Object Symbol function

1.11. Set and Map data structures

  • Structure of the Map
const map = new Map([[1.'one'],
    [2.'two'],
    [3.'three']]);const keys = [...map.keys()]; / / [1, 2, 3]
const values = [...map.values()]; // ['one', 'two', 'three']
map.has(1);
map.get(1);
map.set(4.'four');
map.delete(1);
Copy the code
  • The Set structure
const set = new Set([4.5.6]);
set.has(6);
set.add(7);
set.delete(4);
Copy the code

1.12, the Generator

The Generator function is an asynchronous programming solution provided by ES6 that returns an iterator object.

If multiple internal states exist, the next method must be called. When the done attribute is true, the traversal is complete

function* helloWorldGenerator() {
    console.log(111);
    yield 'hello';
    console.log(222);
    yield 'world';
    console.log(333);
    return 'ending';
}
let hw = helloWorldGenerator();

hw.next();
hw.next();
hw.next();
hw.next(); // {value: undefined, done: true}
Copy the code

1.13, classes, the class

class Point {
    constructor(x, y) {
        this.x = x;
        this.y = y;
    }

    toString() {
        return '(' + this.x + ', ' + this.y + ') '; }}Copy the code

1.14. Modularization

export const a = ' ';
export function a() {};
export {
    a: ' '.b: ' '};export default a;
export default class;
Copy the code

Second, the ES7 (2016).

2.1, includes

Returns true/false to indicate whether an array contains a given value, similar to includes in a string.

Value Target value of the search startIndex Start position of the search. The default value is 0

[1.2.3].includes(3); // true
[1.2.3].includes(3.3); // false
Copy the code

2.2. Exponential operators

One feature of the exponential operator ** is right associative.

// Do not use exponential operators: recursion or math.pow
Math.pow(2.2); / / 4

// Use the exponential operator
2支那2 / / 4
2支那3 / / 8
2支那3支那2 // 2 ** (3 ** 2) = 512
Copy the code

The exponential operator can be combined with the equal sign to form a new assignment operator (**=).

// a = a * a;
let a = 1.5;
a **= 2;

// the same as b = b * b * b;
let b = 4;
b **= 3;
Copy the code

Third, ES8 (2017).

3.1, async/await

Async is the syntactic sugar of a Generator function, essentially replacing the asterisk (*) of a Generator function with async, replacing yield with await, and returning a Promise object.

const gen = function* () {
    const f1 = yield readFile('/etc/fstab');
    const f2 = yield readFile('/etc/shells');
    console.log(f1.toString());
    console.log(f2.toString());
};

const asy = async function () {
    const f1 = await readFile('/etc/fstab');
    const f2 = await readFile('/etc/shells');
    console.log(f1.toString());
    console.log(f2.toString());
};
Copy the code
async function f() {
    const a = await new Promise(function (resolve, reject) {
        throw new Error('Wrong');
    });
    console.log('a:',a)
}

f()
.then(v= > console.log('v:', v))
.catch(e= > console.log('e:', e))
Copy the code

When a Promise object throws an exception, the catch method will be executed. If no catch is used, the page will receive an exception. Try… Catch code block wrap.

3.2, the Object. The values ()

Returns an array of values in an object. Returns the order of the array’s members, as in the traversal of properties.

const obj = { foo: 'bar'.baz: 42 };
Object.values(obj); // ['bar', 42]
Copy the code

3.3, Object. Entries ()

The object.entries () function returns an array of key-value pairs for a given Object’s own enumerable properties.

const obj = {a: 111.b: 222.c: 333};
/ / before use
Object.keys(obj).forEach(key= > {
	console.log('key:'+key+' value:'+obj[key]);
})

/ / when used
for(let [key, value] of Object.entries(obj)){
	console.log(`key: ${key} value:${value}`);
}
Copy the code

3.4, padStart(), padEnd()

Introduced string completion length function, if a string length is not specified, will be completed in the header or tail. PadStart () is used for head completion and padEnd() for tail completion.

  • parameter

The first argument -> the maximum length of string completion to take effect the second argument -> the string used for completion

'x'.padStart(5.'ab') // 'ababx'
'x'.padEnd(5.'ab') // 'xabab'
Copy the code
  • If the length of the original string is equal to or greater than the maximum length, the string completion does not take effect and the original string is returned.
'xxx'.padStart(2.'ab') // 'xxx'
'xxx'.padEnd(2.'ab') // 'xxx'
Copy the code
  • If the second argument is omitted, Spaces are used to complete the length by default.
'x'.padStart(5) // ' x'
'x'.padEnd(5) // 'x '
Copy the code
  • Practical use: Numeric completion specifies the number of digits, prompt string format
'1'.padStart(10.'0') / / "0000000001"
'12'.padStart(10.'0') / / "0000000012"
'123456'.padStart(10.'0') / / "0000123456"

'12'.padStart(10.'YYYY-MM-DD') // "YYYY-MM-12"
'09-12'.padStart(10.'YYYY-MM-DD') // "YYYY-09-12"
Copy the code

3.5. Trailing commas for function arguments

The last argument to the support function has a trailing comma.

function clownsEverywhere(param1, param2,) {
    // ...
}
clownsEverywhere(
  'foo'.'bar',);/ / or
const params = {
    id: '111'.name: 'wqjiao',}Copy the code

The last comma of a function argument is necessary for code that iterates through a version. If a third argument is added to the code, a comma will be added after the original argument, and the change record will show that the position of the original argument has changed.

3.6, Object. GetOwnPropertyDescriptors ()

Object. GetOwnPropertyDescriptors () function is used to retrieve an Object of all their property descriptors, if you don’t have any own properties, it returns null objects.

const obj = {
    name: 'Jine'.get age() { return '18'}};Object.getOwnPropertyDescriptors(obj);
Copy the code

3.7, SharedArrayBuffer

The SharedArrayBuffer object is used to represent a generic, fixed-length buffer of raw binary data, similar to the ArrayBuffer object, which can be used to create views on shared memory. Unlike ArrayBuffer, SharedArrayBuffer cannot be separated.

3.8, Atomics

The Atomics object provides a set of static methods to perform atomic operations on the SharedArrayBuffer object.

Four, ES9 (2018).

4.1. Asynchronous traverser

How to wait for multiple asynchronous procedures to complete when an asynchronous method encounters array traversal.

let data = [1.2.3.4.5.6.7.8.9.0];

// Asynchronous operation
async function doSomething(id) {
    return window.fetch(
        `http://yapi.devops.guchele.com/mock/288/rpm-web/category/child/${id}`,
        {
            headers: {
                Accept: 'application/json'.'Content-Type': 'application/json; charset=utf-8',},mode: 'cors'.redirect: 'follow'.referrer: 'no-referrer'.method: 'GET',
        }
    )
        .then(response= > {
            return response.json();
        })
        .then(res= > {
            console.log(` * *${id}:res**`, res);
            return res;
        });
}
Copy the code
  • You might try this at first, but it doesn’t work as expected
function getRequest() {
    let all = data.map(async item => {
        let res = await doSomething(item);
        return {id: item, res};
    });

    console.log('complete:', all);
}

async function getRequest() {
    let all = [];

    for await (let item of data) {
        doSomething(item);
    }

    console.log('complete');
}
Copy the code

Note: The traversal itself remains synchronous and is completely called before the internal asynchronous function.

  • for... of
async function getRequest() {
    let all = [];

    for (let item of data) {
        let res = await doSomething(item);
        all.push({id: item, res});
    }

    console.log('complete:', all);
}
Copy the code
  • Promise.all
async function getRequest() {
    let all = await Promise.all(
        data.map(async item => {
            let res = await doSomething(item);
            return {id: item, res}; }));console.log('complete:', all);
}
Copy the code

4.2, Promise. Finally ()

A chain of Promise calls either succeeds in reaching the last.then() or fails to trigger.catch(). In some cases, you’ll want to run the same code whether a Promise runs successfully or fails, such as clearing, deleting conversations, closing database connections, etc. .finally() allows you to specify the final logic.

function doSomething() {
    doSomething1()
        .then(doSomething2)
        .then(doSomething3)
        .catch(err= > {
            console.log(err);
        })
        .finally(() = > {
            // finish here!
        });
}
Copy the code

4.3. Expanded and modified for some new features

  • Template string, for invalid parameters, undefined, error removal, etc

  • Rest parameters and extension operators that support other types than groups: objects

  • Regular expression related modifications, such as modifiers, trailing assertions, and so on

    Predicate: x must come before y to match /x(? =y)/ \d+(? = %)/exec (‘ 100% ‘) initiated assertion: [0] = 100 x must be behind the y to match/(? <=y)x/, such as the price of money (? <=\$)\d+/.exec(‘$100’)[0] = ‘100’

Fifth, ES10 (2019).

5.1. TrimStart (), trimEnd()

We’ve probably all used trim()(introduced in ES5) to eliminate whitespace at the beginning and end of a string, and here are two ways to eliminate whitespace.

  • trimStart()Used to eliminate space at the head of the string and preserve space at the tail, with an aliastrimLeft().
' trim '.trimStart(); // "trim "
' trim '.trimLeft(); // "trim "
Copy the code
  • trimEnd()Used to eliminate whitespace at the end of a string and only to eliminate the trailing reserved header, there is an aliastrimRight().
' trim '.trimEnd(); // " trim"
' trim '.trimRight(); // " trim"
Copy the code

See github.com/tc39/propos…

5.2, Flat (), flatMap()

  • flat()

Array dimension reduction, the original multidimensional array internal elements flat, into a one-dimensional array, return the new array, the original array has no impact.

[1.2[3.4]].flat(); // [1, 2, 3, 4]
Copy the code

Flat by default, only one layer can be flattened. If the array is a multi-dimensional array, the number of input parameter layers can be provided

[1.2[3[4.5]]].flat(2); // [1, 2, 3, 4, 5]
[1[2[3]]].flat(Infinity); / / [1, 2, 3]
Copy the code
  • flatMap()

Executes a function on each member of the original Array (equivalent to array.prototype.map ()), and then executes the flat() method on the Array of returned values. This method returns a new array, leaving the original array unchanged. Note that when the return value executes flat(), only one layer is expanded.

5.3, Object. FromEntries

The object.entries () method returns an array of key-value pairs for a given Object’s own enumerable properties, arranged in the same order as for… The in loop returns the same order as it iterates through the object (the difference is that for-In loops also enumerate properties in the prototype chain). The object.fromentries () function passes in a list of key-value pairs and returns a new Object with those key-value pairs. The iterator argument should be an object that implements the @iterator method and returns an iterator object. It generates an array-like object with two elements.

The first element -> is the value used as the attribute key and the second element -> is the value associated with that attribute key

const arr = [ ['0'.'a'], ['1'.'b'], ['2'.'c']].const obj = Object.fromEntries(arr);
console.log(obj); // { 0: "a", 1: "b", 2: "c" }
Copy the code

5.4 Some adjustments and modifications have been made for the previous new features

  • Added the description attribute Symbol. The prototype. The description

  • Function. The prototype. The toString () on the Function instance of toString () method to make the changes

  • Simplify try {} catch {} to modify the catch binding

  • String.prototype.matchAll

Six, ES11 (2020).

6.1 optional chain operators

const obj = {first: {second: 222}};
let nest = obj && obj.first && obj.first.second;
letnest = obj? .first? .second;/ / 222
letnest = obj? .first? .third;// undefined
Copy the code

6.2. The void merge operator

let c = a ? a : b;
let c = a || b;
Copy the code

6.4. Null judgment operator

Determine whether an attribute value is null or undefined, often use | |.

let values = {
    name: null.age: undefined.key: 1.str: ' '.isExist: false.index: 0}; values.name ||'Hello, world! ';
Copy the code

However, in the actual application process, we found that when the attribute value of “”, false, 0 is effective, it obviously cannot fully meet our wishes. A new Null judgment operator was introduced. .

values.str ?? 'Hello, world! ';
Copy the code

It is important to note that with && and | | operators when used at the same time, due to the priority problem, need to use parentheses to package, or you will quote.

6.4. BigInt(Large integer)

JavaScript saves all numbers as 64-bit floating-point numbers, which imposes two major limitations on the representation of values. One is that values are only accurate to 53 binary bits (equivalent to 16 decimal bits), integers beyond which JavaScript cannot accurately represent them, making JavaScript unsuitable for precise scientific and financial calculations. The second value is greater than or equal to 2 to the power of 1024, which JavaScript cannot represent, and will return Infinity. A new data type, BigInt, is introduced to represent only integers and has no limit on the number of digits.

1234 // An ordinary integer
1234n // BigInt

1n + 2n // 3n
Copy the code

Used to calculate

let p = 1;
for (let i = 1; i <= 70; i++) {
    p *= i;
}
console.log(p); / / 1.197857166996989 e+100
Copy the code

BigInt

let p = 1n;
for (let i = 1n; i <= 70n; i++) {
    p *= i;
}
console.log(p);
// `11978571669969891796072783721689098736458938142546425857555362864628009582789845319680000000000000000n
Copy the code

6.5. Dynamic introduction

Nowadays, front-end packaged resources are becoming larger and larger, and front-end application initialization does not need to load all these logical resources. In order to make the first screen render faster, many times dynamic import (load on demand) modules, such as lazy loading of images, can help you improve the performance of the application.

el.onclick = () = > {
    import('/modules/my-module.js')
        .then(module= > {
        // Do something with the module.
        })
        .catch(err= > {
        // load error;})}Copy the code

6.6. Private Fields

class Flower {
    #leafColor = 'green';

    constructor(name) {
        this.name = name;
    }

    getColor() {
        return this.#leafColor; }}const orchid = new Flower('orchid');

console.log(orchid.getColor());
console.log(orchid.#leafColor);
Copy the code

6.7, globalThis

GlobalThis is a new standard method for retrieving globalThis.

globalThis.Array(0.1.2); / / [0]
globalThis.v = { value: true };
Copy the code

Seven, ES12 (2021).

7.1, replaceAll ()

Replace () can only replace the first match that matches the condition. To replace all matches, use g in the regular expression. ReplaceAll (), however, replaces all matches in a string.

'aabbcc'.replace(/b/g.'_'); // "aa__cc"
'aabbcc'.replaceAll('b'.'_'); // "aa__cc"
Copy the code

7.2, Promise. Any

Multiple Promise instance parameters are received and returned as long as one instance succeeds. Promise.any() is like the promise.race () method except that it does not end when a Promise changes to the Rejected state.

async function anyPromise() {
    const promises = [
        fetch('http://yapi.devops.guchele.com/mock/288/rpm-web/category/child/').then(() = > 'a'),
        fetch('http://yapi.devops.guchele.com/mock/288/rpm-web/category/child/').then(() = > 'b'),
        fetch('http://yapi.devops.guchele.com/mock/288/rpm-web/category/child/').then(() = > 'c'),
        // fetch('/rpm-web/category/child/').then(() => 'a'),
        // fetch('/rpm-web/category/child/').then(() => 'b'),
        // fetch('/rpm-web/category/child/').then(() => 'c'),
    ];

    await Promise.any(promises)
        .then(res= > {
            console.log('Promise.any:', res);
        })
        .catch(error= > {
            console.log('Promise. Any abnormal:, error);
        });
}

anyPromise();
Copy the code

This is a big pity. As long as one of them becomes a big pity, the Promise. Any () will return a Promise. If all three operations become Rejected, the await command throws an error.

AggregateError: All promises were rejectedCopy the code

7.3. Numeric delimiters

In everyday life, we may find that some long numbers allow for a separator (usually a comma) for every three digits. For example, 1000 can be written as 1,000 to increase the readability of the number. ECMAScript disables _ to allow JavaScript values to use underscores (_) as separators, but does not specify the number of digits between numeric separators. It allows one separator for every three digits, one for every two digits, and one for every four digits, including integers and decimals.

123 _00= = =12 _300 // true

12345 _00= = =123 _4500 // true
12345 _00= = =1 _234_500 // true
Copy the code
  • Matters needing attention

Two or more characters are not connected to each other before or after the leading or trailing digit. In scientific notation, there are no separators before or after the decimal point

. There are many more new features for the best of you to discover, summarize and implement…

Refer to the website

There are many people who summarize similar ECMAScript features on the Internet. Many features are marked in different years or have different release dates. If you need to summarize or summarize suggestions, please refer to the official website

  • github.com/tc39
  • www.telerik.com/blogs/tag/e…
  • Note. The wiki/frontend/es…

Nanjing 300 Cloud Information Technology Co., LTD. (CHE 300) was founded on March 27, 2014. It is a mobile Internet enterprise rooted in Nanjing and currently located in Nanjing and Beijing. After 7 years of accumulation, the cumulative number of valuation has reached 5.2 billion times, and won the favor of many high-quality investment institutions at home and abroad, such as Sequoia Capital, SAIC Industry Fund. 300 Cloud is an outstanding domestic auto transaction and financial SaaS service provider with independent third party relying on artificial intelligence and standardization of auto transaction pricing and auto financial risk control as its core products.

Welcome to join 300 cloud, witness the booming development of the automobile industry together, look forward to walking with you hand in hand! Java development, Java internship, PHP internship, testing, testing, product manager, big data, algorithm internship, hot recruitment… Official website: www.sanbaiyun.com/ Resume: [email protected], please note from nuggets 😁