This article is not a complete translation, but a summary, interested partners suggest directly read the original, if you have any good suggestions, or wrong places, please leave a comment or @me

The original link: medium.freecodecamp.org/here-are-ex…


Below are 18 features of TC39 completed proposals

ECMAScript 2016

Array.prototype.includes

The includes method of an array makes it very easy to determine if an item exists in the array, including NaN

const arr = [1, 2, 3, 4, If (arr.indexof (3) >= 0) {console.log(true)} includes if (arr.includes(3)) { Console.log (true)} // PS: Cannot search NaN arr.includes(NaN) // true arr.indexof (NaN) // -1Copy the code

Exponentiation Infix operator

Similar to ++ –, ** can be used for quick exponentiation

Math. / / using Math pow pow (7, 2) 49 / / / / using * * 7 * * 2 / / 49Copy the code

ECMAScript 2017

Object.values()

Keys () can be used to obtain the value of an Object, just as object.keys () is used to obtain the key of an Object

const cars = { BMW: 3, Tesla: 2, Toyota: Keys (cars). Map (key => cars[key]) console.log(vals) // [3, 2, Values () const values = object.values (cars) console.log(values) // [3, 2, 1]Copy the code

Object.entries()

Change the key and value of an Object to an array to facilitate traversal of the Object or transform the Object into a Map

// Const cars = {BMW: 3, Tesla: 2, Toyota: 1 } const entries = Object.entries(cars) console.log(entries) // [ ['BMW', 3], ['Tesla', 2], ['Toyota', 1]] // Convert Object to Map const cars = {BMW: 3, Tesla: 2, Toyota: 1} const map1 = new Map(object.entries (cars))Copy the code

Click here for more information about Map

String padding

You can use the String. The prototype. PadStart and String. Prototype. PadEnd to fill a String

// The first argument represents the final length of the string, The second parameter said need to fill the contents of the / / filling '5' from the very beginning. PadStart (10, '*') / / '* * * * * * * * * 5' tail / / start filling '5'. The padEnd (10, '*') / / '5 * * * * * * * * *'Copy the code

Object.getOwnPropertyDescriptors

All the details used to return an Object including (get, set) can be verified with shallow copies of Object (Object.assign) and deep copies of Object (Object.defineproperties)

var Car = { name: 'BMW', price: 1000000, set discount(x) { this.d = x; }, get discount() { return this.d; } } console.log(Object.getOwnPropertyDescriptor(Car, 'discount')); // { // get: [Function: get], // set: [Function: set], // enumerable: true, // configurable: true // } // Object.assign const ElectricCar = Object.assign({}, Car) console.log(Object.getOwnPropertyDescriptor(ElectricCar, 'discount')) // { // value: undefined, // writable: true, // enumerable: true, // configurable: true // } // Object.defineProperties const ElectricCar2 = Object.defineProperties({}, Object.getOwnPropertyDescriptors(Car)) console.log(Object.getOwnPropertyDescriptor(ElectricCar2, 'discount')) // { get: [Function: get], 👈 🏼 👈 🏼 👈 🏼 / / set: [Function: set], 👈 🏼 👈 🏼 👈 🏼 / / enumerable: true, / / configurable: true / /}Copy the code

Add trailing commas in the function parameters

The reason for this is that with tools like Git, only new lines change (probably due to code style).

Async/Await

I think we’re all familiar with this, so let’s do an example

function getUser() { return new Promise(resolve => { setTimeout(() => { resolve('join') }, Setbankbalance () {resolve => {setTimeout(() => {resolve('$1,000')}, Function getAmount() {getUser().then(getBankBalance).then(amount => { Console.log (amount)})} async function getAmount2() {var user = await getUser() var amount = await getBankBalnce(user); console.log(amount) }Copy the code
  • Async itself returns onePromiseSo you can use.thenmethods
  • Async /await is used in parallelPromise.all
    function doulieAfterSec() {
        return new Promise(resolve => {
            setTimeout(resolve(2), 1000)
        })
    }
    
    async function doubleAdded() {
        [a, b] = await Promise.all(doulieAfterSec(), doulieAfterSec())
    }
    Copy the code

ECMAScript 2018

Shared Memory and Atomics

A more advanced feature, or to view the author of the article

  • From Workers to Shared Memory — Lucasfcosta
  • A Cartoon intro to SharedArrayBuffers — Lin Clark
  • Shared Memory and Atomics — Dr. Axel Rauschmayer

Tagged Template literal restriction removed

In the ES2016 and ES2016 specifications, template strings are not allowed to use escape characters, like \u,\x

But in ES2018, by relaxing this requirement and allowing these strings, you can define an Object with the property cooked (which can be any property) for “undefined”, and then define a raw property (which can be any name you want), Store these \u,\x characters in raw

function myTagFunc(str) { 
    console.log(str) // [undefined, raw: [['hi \ubla123abla']]]
    return { "cooked": "undefined", "raw": str.raw[0] }
} 

var str = myTagFunc `hi \ubla123abla`

str // { cooked: "undefined", raw: "hi \ubla123abla" }
Copy the code

Regular expression “dotall” notation (” dotall “flag for Regular exporession)

In regular expressions, the. Symbol can match any character but not a newline character, like \n ‘\r\f, but in ES2018, the /s flag in /first.second/s is added to support the matching of newline characters

// before unsupported /first.second/.test('first\nsecond'); //false // in ES2018 /first.second/s.test('first\nsecond'); //trueCopy the code

Named Group capture of regular expressions (RegExp Named Group Captures)

Provides naming groups in languages like Python, Java, etc. (it was quite useful when writing crawlers in Python), syntax format is (?

…)

/ / the original named group let re1 = / (\ d {4}) - (\ d {2}) - (\ d {2})/let result1 = re1. Exec (' 2015-01-02 ') console. The log (result1) / / ['2015-01-02', '2015', '01', '02', index: 0, input: '2015-01-02', groups: undefined] // let re2 = /(? <year>\d{4})-(? <month>\d{2})-(? <day>\d{2})/ let result2 = re2.exec('2015-01-02') console.log(result2) // ['2015-01-02', '2015', '01', '02', index: 0, input: '2015-01-02', groups: { year: '2015', month: '01', day: '02'}] console.log(result2.groups.year) // 2015Copy the code

You can use \k

to represent the same grouping in the same expression

let sameWords = /(? <fruit>apple|orange)==\k<fruit>/u; sameWords.test('apple==apple') // true sameWords.test('apple==orange') // falseCopy the code

Strings are used by naming groups

FirstName lastName let re = /(? <firstName>[A-Za-z]+) (? <lastName>[A-Za-z]+$)/u 'Raja Rao'.replace(re, '$<lastName>, $<firstName>') // "Rao, Raja"Copy the code

Rest properties for Objects

The use of… The remaining unspecified attributes of an Object can be assigned

let { firstName, age, ...remaining } = {
    firstName: 'john',
    lasttName: 'smith',
    age: 20,
    height: '5.10',
    race: 'martian'
}

firstName // john
age // 20

remaining // { lasttName: 'smith', age: 20, height: '5.10', race: 'martian' }
Copy the code

Can be used to remove unwanted items

let { firstName, age, ... CleanObj} = {firstName: 'John ', lasttName:' Smith ', age: 20, height: '5.10', race: 'Martian'} // cleanObj is the property you really want cleanObj // {lasttName: 'Smith ', age: 20, height: '5.10', race:' Martian '}Copy the code

Spread properties for Objects

. It can also be used to merge old objects to create new ones

const person = { fName: 'john' } const account = { amount: '$1000' } const personAndAccount = { ... person, ... account } personAndAccount // { fName: 'john', amount: '$1000' }Copy the code

RegExp Lookbehind Assertions

Can (? < =…). Gets the content after a specific identity, (?

'#winning'.match(/(? < = #). * /) [0] / / 'winning' 'A gallon of milk is $3.00. The match (/ (? <! \$).*/) // nullCopy the code

Unicode Property Escapes for regular expressions (RegExp Unicode Property Escapes)

For more information, please click here

//The following matches multiple Hindi character /^\p{Script=Devanagari}+$/u.test(' thread thread thread '); //true //PS:there are 3 hindi characters h //The following matches a single Greek character / \ p {Script_Extensions = Greek} / u.t est (" PI "); // trueCopy the code

Promise.prototype.finally()

Promise adds a finally() method that, as the name suggests, is ultimately executed, whether reslove or Reject

let myPromise = new Promise((resolve, reject) => { throw new Error('wrong') }) .then(val => { console.log(val) }) .catch(e => { throw new Error('wrong') }) .finally(() => {console.log(' this will always be executed ')})Copy the code

Asynchronous Iteration

As the name implies, a for-await-of iteration that supports inclusion of asynchrony

const promises = [ new Promise(resolve => resolve(1)), new Promise(resolve => resolve(2)), Async function test1() {for (const obj of promises) {console.log(obj); async function test1() {for (const obj of promises) {console.log(obj); }} // Use for-await-of async function test2() {for await(const obj of promises) {console.log(obj) Test1 ()// Promise, Promise, Promise test2()// 1,2,3...Copy the code

The original link: medium.freecodecamp.org/here-are-ex…