【文】深入探索 ES2018 及 ES2019

A Deep Dive into ES2018 and ES2019

ECMAScript (ES) is the standard specification for JavaScript, and it receives updates every year. In this article, we will explore two recent versions of the language: ES2018 and ES2019. We will dive deep into their new features and discuss their significance in web development.

ES2018

Asynchronous Iteration

Asynchronous iteration is a new feature added to ES2018 that allows us to iterate over asynchronous data sources such as streams or promises.

----- --------- -------------- -
  --- - - --
  ----- ------ -
    ----- --- --------------- -- ------------------- -------
    ----- ----
  -
-

------ -- -- -
  --- ----- ------ --- -- --------------- -
    -----------------
  -
-----

In the above example, asyncCounter is an asynchronous generator that increments a counter every second infinitely. The for-await-of loop allows us to asynchronously iterate over the values generated by the asynchronous generator.

Rest/Spread Properties for Objects

ES2018 introduces the rest/spread properties for objects, which allows us to extract and merge properties from and into objects more easily.

----- ------ - - ----- ------ ---- --- ------- ------ --
----- - ----- ------- - - -------

------------------ -- -----
------------------ -- - ---- --- ------- ------ -

----- -------- - - ---------- --------- ----------- --

---------------------- -- - ----- ------ ---- --- ------- ------- --------- ----------- -

In the above example, we use the rest operator to extract the name property from the person object and store the remaining properties in the rest object. We also use the spread operator to merge the person object into the employee object and add a new position property.

ES2019

Array.prototype.{flat,flatMap}

The flat method is added to the Array prototype in ES2019, which allows us to flatten nested arrays recursively with a depth parameter.

----- --- - --- -- --- -- --- -----
------------------------ -- --- -- -- -- --- ---
------------------------- -- --- -- -- -- -- --

The flatMap method is also added to the Array prototype, which allows us to map and flatten an array at the same time.

----- --- - --- -- -- ---
------------------------- -- -- - ----- -- --- -- -- --

Optional Catch Binding

ES2019 introduces optional catch binding, which allows us to omit the error parameter in a catch block.

--- -
  -- -- --------- ---- --- ----- -- -----
- ----- -
  -- ------ --- ----- ------- --- ----- ---------
-

In the above example, we omit the error parameter in the catch block since we don't need it.

Conclusion

ES2018 and ES2019 introduce many useful features that can improve our productivity and make our code more concise and readable. As developers, it is important to keep up-to-date with the latest language features and incorporate them into our projects where appropriate.

来源:JavaScript中文网 ,转载请注明来源 本文地址:https://www.javascriptcn.com/post/32172