Skip to content

Commit

Permalink
docs: update ES2022
Browse files Browse the repository at this point in the history
  • Loading branch information
ruanyf committed Jun 25, 2022
1 parent e0772de commit a837d8f
Show file tree
Hide file tree
Showing 6 changed files with 318 additions and 264 deletions.
12 changes: 11 additions & 1 deletion docs/array.md
Original file line number Diff line number Diff line change
Expand Up @@ -843,7 +843,7 @@ arr.flatMap(function callback(currentValue[, index[, array]]) {

这是因为方括号运算符`[]`在 JavaScript 语言里面,不仅用于数组,还用于对象。对于对象来说,方括号里面就是键名,比如`obj[1]`引用的是键名为字符串`1`的键,同理`obj[-1]`引用的是键名为字符串`-1`的键。由于 JavaScript 的数组是特殊的对象,所以方括号里面的负数无法再有其他语义了,也就是说,不可能添加新语法来支持负索引。

为了解决这个问题,现在有一个[提案](https://github.com/tc39/proposal-relative-indexing-method/)为数组实例增加了`at()`方法,接受一个整数作为参数,返回对应位置的成员,支持负索引。这个方法不仅可用于数组,也可用于字符串和类型数组(TypedArray)。
为了解决这个问题,[ES2022](https://github.com/tc39/proposal-relative-indexing-method/) 为数组实例增加了`at()`方法,接受一个整数作为参数,返回对应位置的成员,并支持负索引。这个方法不仅可用于数组,也可用于字符串和类型数组(TypedArray)。

```javascript
const arr = [5, 12, 8, 130, 44];
Expand All @@ -853,6 +853,16 @@ arr.at(-2) // 130

如果参数位置超出了数组范围,`at()`返回`undefined`

```javascript
const sentence = 'This is a sample sentence';

sentence.at(0); // 'T'
sentence.at(-1); // 'e'

sentence.at(-100) // undefined
sentence.at(100) // undefined
```

## 数组的空位

数组的空位指的是,数组的某一个位置没有任何值,比如`Array()`构造函数返回的数组都是空位。
Expand Down
17 changes: 2 additions & 15 deletions docs/async.md
Original file line number Diff line number Diff line change
Expand Up @@ -724,7 +724,7 @@ async function logInOrder(urls) {

## 顶层 await

根据语法规格`await`命令只能出现在 async 函数内部,否则都会报错。
早期的语法规定是`await`命令只能出现在 async 函数内部,否则都会报错。

```javascript
// 报错
Expand All @@ -733,7 +733,7 @@ const data = await fetch('https://api.example.com');

上面代码中,`await`命令独立使用,没有放在 async 函数里面,就会报错。

目前,有一个[语法提案](https://github.com/tc39/proposal-top-level-await),允许在模块的顶层独立使用`await`命令,使得上面那行代码不会报错了。这个提案的目的,是借用`await`解决模块异步加载的问题。
[ES2022](https://github.com/tc39/proposal-top-level-await) 开始,允许在模块的顶层独立使用`await`命令,使得上面那行代码不会报错了。它的只要目的,是使用`await`解决模块异步加载的问题。

```javascript
// awaiting.js
Expand All @@ -749,19 +749,6 @@ export { output };

上面代码中,模块`awaiting.js`的输出值`output`,取决于异步操作。我们把异步操作包装在一个 async 函数里面,然后调用这个函数,只有等里面的异步操作都执行,变量`output`才会有值,否则就返回`undefined`

上面的代码也可以写成立即执行函数的形式。

```javascript
// awaiting.js
let output;
(async function main() {
const dynamic = await import(someMission);
const data = await fetch(url);
output = someProcess(dynamic.default, data);
})();
export { output };
```

下面是加载这个模块的写法。

```javascript
Expand Down
Loading

0 comments on commit a837d8f

Please sign in to comment.