Rest/Spread properties

rest

Copies the remaining properties of the object into a new object.

let{ x, y, ... z } = { x: 1, y: 2, a: 3, b: 4 }; x; // 1 y; // 2 z; // { a: 3, b: 4 }Copy the code

spread

Quickly copy the properties of an object to another object.

letn = { x, y, ... z }; n; // { x: 1, y: 2, a: 3, b: 4 }Copy the code

Asynchronous iterators and asynchronous iterables

Unlike iterators, the next() method of an asynchronous iterator returns a promise containing {value, done}.

const { value, done } = syncIterator.next();

asyncIterator.next().then(({ value, done}) = > / *... * /);Copy the code

As you can see, syncIterator is an asynchronous iterator. It can be generated using an asynchronous generator. The following shows how to define an asynchronous generator function.

Asynchronous Generator function


async function* asyncGen() {
  let p1 = new Promise((resolve, reject) =>{
      setTimeout(()=>{ resolve(1); }, 1000)});let p2 = new Promise((resolve, reject) =>{
      setTimeout(()=>{ resolve(2); }, 1000)}); yield await p1; yield await p2 }Copy the code

for-await-of

Es2018 provides new traversal syntax for traversing asynchronous iterators.

for await (const val of asyncGen()) {
  console.log(val);
}
Copy the code

Promise.prototype.finally()

Promise. Prototype. Finally () whether or not the Promise of the execution result is success or failure, in the Promise after completion of execution, will trigger a callback function. Common application scenarios such as hiding loading animation after an Ajax request succeeds or fails.

fetch('https://demo.com/endpoint')
.then(res => {
    // ...
})
.catch(err => {
    // ...
})
.finally(() => {
    // do sth no matter success or failure
})
Copy the code

Tagged template string and escape sequence

Starting with ES2016, tagged template strings will escape strings beginning with \u, \u{}, \x, or \ plus a number. However, a syntax error is reported if a non-escaped character starting with one of these characters appears in the template string.

In ES2018, the restriction on tagged characters is removed. If the template is parsed properly, the escaped character value can be obtained. Otherwise, undefined is returned.

function latex(str) { 
 return { "cooked": str[0], "raw": str.raw[0] }
} 

latex`\unicode`
// { cooked: undefined, raw: "\unicode"}

Copy the code

As you can see, we don’t get an error when we use STR [0] to get the escaped character. The string “\ Unicode “is normally obtained from str.raw[0].

Regular related properties

S (dotAll) model

We know metacharacters. Cannot match newlines such as \r \n \u{2048} \u{2049}.

In ES2018, a new flag s has been added to regular expressions to represent the attribute dotAll. So that. Can match any character, including newlines.

const re = /foo.bar/s;
re.test('foo\nbar'); / / -trueRe. DotAll / / -trueRe. Flags / / -'s'
Copy the code

Name the capture group named Capture Groups

Partial matches captured by the () syntax can be referenced by numeric indexes in regular expressions. Such as

let re = /(\d{4})-(\d{2})-(\d{2})/;
let result = re.exec('2015-01-02'); console.log(result[1],result[2],result[3]); / / 2015, 01, 02Copy the code

The ability to name capture groups is provided in ES2018. We can pass (?

…) Syntax names the capture group.

letre = /(? <year>\d{4})-(? <month>\d{2})-(? <day>\d{2})/u;let result = re.exec('2015-01-02');
// result.groups.year === '2015';
// result.groups.month === '01';
// result.groups.day === '02';
Copy the code

Or simplify the code with deconstruction syntax:

let{groups: {year, month, day}} = /(? <year>\d{4})-(? <month>\d{2})-(? <day>\d{2})/u.exec('2015-01-02');
console.log(`year: ${year}, month: ${month}, day: ${day}`);  // prints year: 2015, month: 01, day: 02
Copy the code

After assertion

In ES5, regex only supports preemptive assertions. Such as:

Forward antecedent assertion /x(? =y)/ indicates that the position after x must be y.

Negative preemptive assertion /x(? ! Y)/ means that the position after the x character cannot be equal to y.

Support for subsequent assertions has been added in ES2018. Such as:

/ (? <=y)x/ indicates that the position before the character x must be y.

/ (? <! Y)x/ indicates that the position before x cannot be y.

letre = /(? <=java)script/; consle.log(re.test('javascript'));
// true
Copy the code

Unicode property escapes

Unicode Property Escapes make it possible to access these Unicode character properties locally within JS regular expressions. For example, the pattern \p {Script_Extensions = Greek} matches any symbol in the Greek script.

const regexGreekSymbol = /\p{Script_Extensions=Greek}/u;
regexGreekSymbol.test('PI.); / / -true
Copy the code

Optional catch parameter

Es2018 has changed the syntax so that catch omits parentheses without using arguments. Such as:

try {
  // try to use a web feature which may not be implemented
} catch (unused) {
  // fall back to a less desirable web feature with broader support
}
Copy the code

The above code can be written under the new specification:

try {
  // try to use a web feature whichMay not be implemented} catch {//Copy the code

JSON superset

We know that ES5 uses json. parse to convert a JSON string into a JS JSON object. The exception to this rule is that json text contains unescaped newlines such as \u2028,\u2029.

Es2018 has been extended to support all JSON text, so unescaped newlines are also allowed.

const LS = "";
const PS = eval("'\u2029'");
Copy the code

The above code snippet will not cause syntax errors in browsers that implement the ES2018 specification, and will cause syntax errors if not. Try it yourself.