Javascript 简明教程

JavaScript - ECMAScript 2018

JavaScript 的 ECMAScript 2018 版本发行于 2018 年。ECMAscript 2017 对语言进行了重大增强。此版本中引入的两个重要功能分别是 asynchronous iteration ,用于改进异步操作的处理,以及 promise finally() ,用于无论 Promise 状态如何都执行代码。本章将讨论 ECMAScript 2018 中所有新增加的功能。

The ECMAScript 2018 version of JavaScript was released in 2018. ECMAScript 2017 introduced singnificant enhancement to the language. Two important features introduced in this version are asynchronous iteration for improved handling of asynchronous operations, and promise finally() to execute code regardless of promise resolution. This chapter will discuss all the new added features in ECMAScript 2018.

New Added Features in ECMAScript 2018

以下是在 JavaScript 的 ECMAScript 2018 版本中新增的方法、功能等。

Here are the new methods, features, etc., added to the ECMAScript 2018 version of JavaScript.

  1. Asynchronous iteration

  2. New features of the RegExp() Object

  3. Promise.finally()

  4. Rest object properties

这里,我们详细解释了每项特性。

Here, we have explained each feature in detail.

JavaScript Asynchronous Iteration

你还可以在 for 循环中使用“await”关键字进行异步迭代。

You can also use the 'await' keyword with the for loop to make asynchronous iterations.

例如,你在迭代多个 Promise,并在每次迭代中都需要停止代码执行,直到当前 Promise 被解析或拒绝。

For example, you are iterating multiple promises, and in each iteration, you need to stop the code execution until the current promise gets resolved or rejected.

Example

在以下代码中,我们定义了名为 gen_function 的 async generator 函数。gen_func() 函数使用循环进行 5 次迭代。在每次迭代中,它等待解析 Promise 并返回 p。

In the below code, we have defined the async generator function named gen_function. The gen_func() function makes 5 iterations using the loop. In each iteration, it awaits to resolve the promise and returns p.

在 test() 函数中,我们使用“await”关键字和 for 循环进行异步迭代。它会在每 0.5 秒后更新输出。

In the test() function, we used the 'await' keyword with the for loop to make asynchronous iterations. It updates the output after every 0.5 seconds.

<html>
<body>
   <div id = "demo"> </div>
   <script>
      const output = document.getElementById("demo");
      // Generator function
      async function* gen_function() {
         for (let p = 0; p < 5; p++) {
            await new Promise(res => setTimeout(res, 500));
            yield p;
         }
      }
      async function test() {
         for await (const ele of gen_function()) {
            output.innerHTML += "Returned element is: " + ele + "<br>";
         }
      }
      test();
   </script>
</body>
</html>
Returned element is: 0
Returned element is: 1
Returned element is: 2
Returned element is: 3
Returned element is: 4

New features of the RegExp() object

在 ECMAScript 2018 中,引入了以下四个新正则表达式功能 −

In ECMAScript 2018, the following four new regular expression features were introduced −

  1. Unicode Property Escapes (\p{…​})

  2. Lookbehind Assertions (?⇐ ) and (?<! )

  3. Named Capture Groups

  4. s (dotAll) Flag

Unicode Property Escapes (\p{…​})

Unicode 属性转义允许你转义 Unicode 字符。你需要在花括号中用“\p”后跟 Unicode。

The Unicode property escape allows you to escape the Unicode character. You need to represent the Unicode in the curly braces followed by the '\p'.

Example

在以下代码中,我们使用正则表达式来检查文本是否包含字母,方法是使用 Unicode 属性访问。

In the below code, we use the regular expression to check whether the tet contains the letter using the Unicode property access.

<html>
<body>
   <div id = "output1">regex.test('Y'):  </div>
   <div id = "output2">regex.test('6'):  </div>
   <script>
      const regex = /\p{Letter}/u; // To Match letters only
      document.getElementById("output1").innerHTML += regex.test('Y'); // true
      document.getElementById("output2").innerHTML += regex.test('6'); // false
   </script>
</body>
</html>
regex.test('Y'): true
regex.test('6'): false

Lookbehind Assertions (?⇐ ) and (?<! )

后顾断言允许你查找特定子模式后跟特定子模式。肯定后顾断言等于 ?⇐,否定后顾断言是 ?<!。

The Lookbehind assertion allows you to find a particular subpattern followed by a particular sub patter. The positive look-behind assertion is equal to ?⇐, and the negative look-behind assertion is ?<!.

Example

在以下代码中,我们使用后顾断言找某个单词后面紧跟“@”,它将找到“@”模式后面的单词。

In the below code, we are looking for a word after the '@' using the look behind the assertion. It finds words after the '@' pattern.

<html>
<body>
   <div id = "output">lookBeind.exec('abcd@domain.com')[0]:  </div>
   <script>
      const lookBeind = /(?<=@)\w+/;
      document.getElementById("output").innerHTML +=
	  lookBeind.exec('abcd@tutorialspoint.com')[0]; // Prints domain
   </script>
</body>
</html>
lookBeind.exec('abcd@domain.com')[0]: tutorialspoint

Named Capture Groups

您可以为正则表达式的每个组指定一个惟一名称。组名称让从字符串中提取模式变得简单。

You can give a unique name to each group of the regular expression. The group names make it easy to extract the patterns from the string.

Example

在下面的代码中,我们已经定义了匹配日期模式的正则表达式。此外,我们已经命名了年份、月份和日期组。

In the code below, we have defined the regular expression to match the date pattern. Also, we have named the groups' year, month, and day.

之后,我们使用组名称从日期中提取年份。

After that, we extracted the year from the date using the group name.

<html>
<body>
   <div id = "output">The year of the date is: </div>
   <script>
      const datePattern = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;
      const match = datePattern.exec('2023-08-22');
      document.getElementById("output").innerHTML += match.groups.year;
   </script>
</body
</html>
The year of the date is: 2023

s (dotAll) Flag

'.'(点)字符匹配正则表达式中的除换行符以外的任何字符。如果您也想使用 '.' 字符匹配换行符,您需要使用 '/s' 标志,如下面示例所示。

The '.' (dot) character matches any character except the new line in a regular expression. If you also want to match the new line using the '.' Character, you need to use the '/s' flag, as shown in the example below.

Example

在下面的代码中,我们在正则表达式模式中添加了 '.' 字符以匹配任何字符,并且添加了 \s 标志。

In the below code, we have added the '.' Character in the regular expression pattern to match any character, and also added \s flag.

在输出中,您可以看到 '.' 字符也匹配 '\n'。

In the output, you can see that '.' character also matches with the '\n'.

<html>
<body>
   <div id = "output">strRegex.test('Hello\nprogrammers'):  </div>
   <script>
      const strRegex = /Hello.programmers/s;
      document.getElementById("output").innerHTML +=
	  strRegex.test('Hello\nprogrammers');
   </script>
</body>
</html>
strRegex.test('Hello\nprogrammers'): true

JavaScript Promise finally()

您可以将 finally() 块与 promises 一起使用,以便在 promise 解析或拒绝后执行特定的代码。它类似于 try…​catch…​finally 块。

You can use the finally() block with promises to execute the particular code after the promise gets resolved or rejected. It is similar to the try…​catch…​finally block.

Example

在下面的示例中,我们创建了 promise,并将其存储在 getData 变量中。promise 在 1000 毫秒后解析。

In the example below, we created the promise and stored it in the getData variable. The promise gets resolved after 1000 milliseconds.

之后,我们使用 'then…​finally' 块来执行 promise。在输出中,您可以观察到 'finally' 块的代码始终得到执行。

After that, we use the 'then…​finally', block to execute the promise. In the output, you can observe that code of the 'finally' block always gets executed.

<html>
<body>
   <div id = "output"> </div>
   <script>
      const getData = new Promise((res, rej) => {
         setTimeout(() => {
            res("Promise resolved!");
         }, 1000);
      });
      getData
         .then(result => {
            document.getElementById("output").innerHTML += result + "<br>";
         })
         .finally(() => {
            document.getElementById("output").innerHTML += "In the finally block!";
         });
   </script>
</body>
</html>
Promise resolved!
In the finally block!

JavaScript Rest Object Properties

在解构对象时,可以使用展开运算符。展开运算符允许您以对象格式将剩余属性收集到单个变量中。

You can use the spread operator while destructuring the objects. The spread operator allows you to collect the remaining properties in a single variable in the object format.

Example

在下面的示例中,numbers 对象包含 4 个属性。在解构时,我们获取 num1 属性的值,并使用展开运算符将其他属性存储在 nums 变量中。

In the example below, the numbers object contains 4 properties. While destructuring, we get the value of the num1 property and store other properties in the nums variable using the spread operator.

<html>
<body>
   <div id = "output"> </div>
   <script>
      const numbers = {
         num1: 40,
         num2: 50,
         num3: 80,
         num4: 90,
      }
      const { num1, ...nums } = numbers;
      document.getElementById("output").innerHTML =
	  "num1 = " + num1 + "<br>" +
      "nums = " + JSON.stringify(nums);
    </script>
</body>
</html>
num1 = 40
nums = {"num2":50,"num3":80,"num4":90}