Iterator.prototype.toArray()

Experimental: This is an experimental technology
Check the Browser compatibility table carefully before using this in production.

Iterator 实例的 toArray() 方法创建一个新的 Array 实例,其中填充了迭代器生成的元素。

¥The toArray() method of Iterator instances creates a new Array instance populated with the elements yielded from the iterator.

语法

¥Syntax

js
toArray()

参数

¥Parameters

没有任何。

¥None.

返回值

¥Return value

一个新的 Array 实例,包含迭代器中的元素(按生成顺序排列)。

¥A new Array instance containing the elements from the iterator in the order they were produced.

示例

¥Examples

使用 toArray()

¥Using toArray()

iterator.toArray() 相当于 Array.from(iterator)[...iterator],只不过当涉及多个迭代器辅助方法时,它更容易链接。以下示例创建一个迭代器,该迭代器生成斐波那契数列中的项、获取前 10 项、过滤掉奇数并将结果转换为数组:

¥iterator.toArray() is equivalent to Array.from(iterator) and [...iterator], except that it's easier to chain when multiple iterator helper methods are involved. The following example creates an iterator that yields terms in the Fibonacci sequence, takes the first 10 terms, filters out the odd numbers, and converts the result to an array:

js
function* fibonacci() {
  let current = 1;
  let next = 1;
  while (true) {
    yield current;
    [current, next] = [next, current + next];
  }
}

const array = fibonacci()
  .take(10)
  .filter((x) => x % 2 === 0)
  .toArray();

console.log(array); // [2, 8, 34]

请注意,最好将调用 toArray() 作为处理的最后一步。例如,fibonacci().take(10).toArray().filter(...) 效率较低,因为迭代器助手很懒惰并且避免创建临时数组。

¥Note that it's a good idea to call toArray() as a last step of your processing. For example, fibonacci().take(10).toArray().filter(...) is less efficient, because iterator helpers are lazy and avoids creating a temporary array.

规范

Specification
Iterator Helpers
# sec-iteratorprototype.toarray

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看