javaScript ES7 ES8 ES9 new features

References:  https://tuobaye.com/2018/11/27/%E7%BB%86%E8%A7%A3JavaScript-ES7-ES8-ES9-%E6%96%B0%E7%89%B9%E6 % 80% A7 /

ES7

1. Array.prototype.includes()方法

['a', 'b', 'c', 'd'].includes('b')         // true
['a', 'b', 'c', 'd'].includes('b', 1)      // true
['a', 'b', 'c', 'd'].includes('b', 2)      // false
var ary1 = [NaN];
console.log(ary1.indexOf(NaN))//-1
console.log(ary1.includes(NaN))//true

2. exponentiation operator (**)

Use **instead Math.pow.

4 ** 3

Equivalent to

Math.pow(4,3)
let n = 4;
n **= 3;

SS8

1. Async Functions

Async Functions that is, we often say Async / Await. Async / Await a deal for JS asynchronous operation syntactic sugar that can help us get rid of callback hell, write more elegant code.

Popular understanding of the role of async keyword tells the compiler that a function for calibration should be treated differently. When the compiler when the calibration function encounters await keywords in to? Temporarily stopped, calibrated to the function await post-processing is completed, then the appropriate action . If this function is fulfilled, and the return value is the resolve value, otherwise get it is reject value.

Take an ordinary written promise to compare:

async function asyncFunc() {
    const result = await otherAsyncFunc();
    console.log(result);
}

// Equivalent to:
function asyncFunc() {
    return otherAsyncFunc()
    .then(result => {
        console.log(result);
    });
}

Parallel processing of multiple functions:

async function asyncFunc() {
    const [result1, result2] = await Promise.all([
        otherAsyncFunc1(),
        otherAsyncFunc2(),
    ]);
    console.log(result1, result2);
}

// Equivalent to:
function asyncFunc() {
    return Promise.all([
        otherAsyncFunc1(),
        otherAsyncFunc2(),
    ])
    .then([result1, result2] => {
        console.log(result1, result2);
    });
}

Error handling:

async function asyncFunc() {
    try {
        await otherAsyncFunc();
    } catch (err) {
        console.error(err);
    }
}

// Equivalent to:
function asyncFunc() {
    return otherAsyncFunc()
    .catch(err => {
        console.error(err);
    });
}

2. SharedArrayBuffer和Atomics

SharedArrayBuffer SharedArrayBuffer allow sharing between a plurality of objects and a main thread workers bytes. This sharing has two advantages:

  • Data can be shared between workers faster.
  • Coordination between workers easier and faster (and postMessage () compared)

API:

  Constructor: new SharedArrayBuffer (length)

  Static properties: SharedArrayBuffer [Symbol.species]

  Examples of attributes: SharedArrayBuffer.prototype.byteLength ()

              SharedArrayBuffer.prototype.slice(start, end)

Atomics method can be used to synchronize with other workers. The following two operations that allow you to read and write data, and will not be rearranged compiler:

  • Atomics.load(ta : TypedArray, index)
  • Atomics.store(ta : TypedArray, index, value : T)

The idea is to use the most routine operations to read and write data, while Atomics operation (load, store, and other operations) to ensure security to read and write. Typically, to use a custom synchronization mechanism (e.g.) may be implemented based on Atomics .

API: 

The main function of the Atomic operand must be an instance Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array or the Uint32Array. It must be wrapped in a SharedArrayBuffer.

    • Atomics.load (ta: TypedArray, index) : T
      are read and returned ta [index] in the element array return value specified position?.
    • Atomics.store (ta: TypedArray, index, value: T): T
      is written in the value ta [index], and returns the value.
    • Atomics.exchange (ta: TypedArray, index, value: T): T
      The element ta [index] in the set to value, and returning to the index value of the previous index.
    • Atomics.compareExchange (ta: TypedArray, index, expectedValue, replacementValue): T
      current element if ta [index] is on expectedValue, then use replacementValue replaced. And returns the index of the original index (or not change) value.
    • Atomics.add (ta: TypedArray, index, value): T
      performs ta [index] + = value and returns ta [index] of the original value.
    • Atomics.sub (ta: TypedArray, index, value): T
      performs ta [index] - = value and returns ta [index] of the original value.
    • Atomics.and (ta: TypedArray, index, value): T
      performs ta [index] & = value and returns ta [index] of the original value.
    • Atomics.or (ta: TypedArray, index, value): T
      performs ta [index] | = value and returns ta [index] of the original value.
    • Atomics.xor (ta: TypedArray, index, value): T
      performs ta [index] ^ = value and returns ta [index] of the original value.
    • Atomics.wait (ta: Int32Array, index, value, timeout = Number.POSITIVE_INFINITY): ( 'not-equal' | 'ok' | 'timed-out')
      if ta [index] is not the current value of the value, returns' not-equal '. Otherwise (equal value) continue to wait until we wake up by Atomics.wake () or wait until a timeout. In the former case, return 'ok'. In the latter case, return 'timed-out'. timeout in milliseconds. Remember that this function performs the operation: "If ta [index] to value, then continue to wait."
    • Atomics.wake (ta: Int32Array, index, count)
      Wake wait on ta [index] of the count workers.

3. Object.values and Object.entries

const obj = { 10: 'xxx', 1: 'yyy', 3: 'zzz' };
Object.values(obj); // ['yyy', 'zzz', 'xxx']

Object.values('es8'); // ['e', 's', '8']
const obj = ['e', 's', '8'];
Object.entries(obj); // [['0', 'e'], ['1', 's'], ['2', '8']]

const obj = { 10: 'xxx', 1: 'yyy', 3: 'zzz' };
Object.entries(obj); // [['1', 'yyy'], ['3', 'zzz'], ['10': 'xxx']]

Object.entries('es8'); // [['0', 'e'], ['1', 's'], ['2', '8']]

4. String padding

An increase of 2 functions as String objects: padStart and padEnd. Padding the string header and trailer, in order to make the length of the resulting string to achieve a given length (targetLength). You can by a specific character or string, or the default spaces to fill it.

str.padStart(targetLength [, padString])
str.padEnd(targetLength [, padString])

"es8'.padStart (2);          // 'es8' 
'es8'.padStart (5);          // 'es8' 
'es8'.padStart (6' Woof ');  // 'wooes8' 
'es8'.padStart (14, wow);  // 'wowwowwowwoes8' 
'es8'.padStart (7, 0);     // '0000es8'
 
'es8'.padEnd (2);            // 'es8' 
'es8'.padEnd (5);            // 'es8' 
'es8'.padEnd (6' Woof ');    // 'es8woo' 
'es8'.padEnd (14, wow);    // ' 
es8wowwowwowwo ' ' es8'.padEnd (7, '6');       // 'es86666'

5. Object.getOwnPropertyDescriptors

const obj = { 
  get es7() { return 777; },
  get es8() { return 888; }
};
Object.getOwnPropertyDescriptor(obj);
// {
//   es7: {
//     configurable: true,
//     enumerable: true,
//     get: function es7(){}, //the getter function
//     set: undefined
//   },
//   es8: {
//     configurable: true,
//     enumerable: true,
//     get: function es8(){}, //the getter function
//     set: undefined
//   }
// }

6. Trailing comma

// parameter defined 
function foo ( 
    the param1, 
    param2, 
) {} 

// function call 
foo (
     'ABC' ,
     'DEF' , 
); 

// object 
the let obj = { 
    First: 'Jane' , 
    Last: 'Doe ' , 
}; 

// array of 
the let ARR = [
     ' Red ' ,
     ' Green ' ,
     ' Blue ' , 
];

ES9 new features

1. iterator Asynchronous: Asynchronous iterator object next () method returns a Promise , with similar values of parsed regular iterator.

async function example() {
  // 普通迭代器:
  const iterator = createNumberIterator();
  iterator.next(); // Object {value: 1, done: false}
  iterator.next(); // Object {value: 2, done: false}
  iterator.next(); // Object {value: 3, done: false}
  iterator.next(); // Object {value: undefined, done: true}

  // 异步迭代器:
  const asyncIterator = createAsyncNumberIterator();
  const p = asyncIterator.next(); // Promise
  await p;// Object {value: 1, done: false}
  await asyncIterator.next(); // Object {value: 2, done: false}
  await asyncIterator.next(); // Object {value: 3, done: false}
  await asyncIterator.next(); // Object {value: undefined, done: true}
}

2. Rest / Spread Properties

rest parameters and expand the operator, this feature has been introduced in the ES6, ES6 but only in the array . In the ES9 for the object it is provided like an array of rest and extended operator parameters.
const obj = {
  a: 1,
  b: 2,
  c: 3
}
const { a, ...param } = obj;
  console.log(a)     //1
  console.log(param) //{b: 2, c: 3}

function foo({a, ...param}) {
  console.log(a);    //1
  console.log(param) //{b: 2, c: 3}
}

3.  Promise.prototype.finally()

finally callback will always be executed.

promise
  .then(result => {···})
  .catch(error => {···})
  .finally(() => {···});

4. Name capturing group

ES9 capture group can be identified by the name:

(?<year>[0-9]{4})

before:

const RE_DATE = /([0-9]{4})-([0-9]{2})-([0-9]{2})/;

const matchObj = RE_DATE.exec('1999-12-31');
const year = matchObj[1]; // 1999
const month = matchObj[2]; // 12
const day = matchObj[3]; // 31

after:

RE_DATE = const / (? <year> [0-9] {}. 4) - (? <month The> [0-9] {2}) - (? <DATE> [0-9] {2}) / ; 

matchObj const = RE_DATE.exec ( '1999-12-31' ); 
const year = matchObj.groups.year; // 1999 
const = month The matchObj.groups.month; // 12 is 
const = Day matchObj.groups.date; / / 31 

// use syntax easier deconstruction 
const {Groups: Day {,}} = RE_DATE.exec year ( '1999-12-31' ); 
the console.log (year); // 1999 
the console.log (Day) ; // 31

 



Guess you like

Origin www.cnblogs.com/ceceliahappycoding/p/11354353.html