Iterator.prototype.map()

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

Iterator 实例的 map() 方法返回一个新的 迭代器助手,它产生迭代器的元素,每个元素都由映射函数转换。

¥The map() method of Iterator instances returns a new iterator helper that yields elements of the iterator, each transformed by a mapping function.

语法

¥Syntax

js
map(callbackFn)

参数

¥Parameters

callbackFn

对迭代器生成的每个元素执行的函数。它的返回值由迭代器助手生成。使用以下参数调用该函数:

element

当前正在处理的元素。

index

当前正在处理的元素的索引。

返回值

¥Return value

新的 迭代器助手。每次调用迭代器助手的 next() 方法时,它都会从底层迭代器获取下一个元素,应用 callbackFn 并产生返回值。当底层迭代器完成时,迭代器助手也完成(next() 方法生成 { value: undefined, done: true })。

¥A new iterator helper. Each time the iterator helper's next() method is called, it gets the next element from the underlying iterator, applies callbackFn, and yields the return value. When the underlying iterator is completed, the iterator helper is also completed (the next() method produces { value: undefined, done: true }).

描述

¥Description

迭代器助手相对于数组方法的主要优点是它们能够使用无限迭代器。通过无限迭代器,map() 允许你创建一个新的迭代器,该迭代器在迭代时会生成转换后的元素。

¥The main advantage of iterator helpers over array methods is their ability to work with infinite iterators. With infinite iterators, map() allows you to create a new iterator that, when iterated, produces transformed elements.

示例

¥Examples

使用映射()

¥Using map()

以下示例创建一个迭代器,该迭代器生成斐波那契序列中的项,将其转换为每个项平方的新序列,然后读取前几个项:

¥The following example creates an iterator that yields terms in the Fibonacci sequence, transforms it into a new sequence with each term squared, and then reads the first few terms:

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

const seq = fibonacci().map((x) => x ** 2);
console.log(seq.next().value); // 1
console.log(seq.next().value); // 1
console.log(seq.next().value); // 4

将 map() 与 for...of 循环结合使用

¥Using map() with a for...of loop

当你不手动滚动迭代器时,map() 最方便。因为迭代器也是可迭代的,所以你可以使用 for...of 循环迭代返回的助手:

¥map() is most convenient when you are not hand-rolling the iterator. Because iterators are also iterable, you can iterate the returned helper with a for...of loop:

js
for (const n of fibonacci().map((x) => x ** 2)) {
  console.log(n);
  if (n > 30) {
    break;
  }
}

// Logs:
// 1
// 1
// 4
// 9
// 25
// 64

这相当于:

¥This is equivalent to:

js
for (const n of fibonacci()) {
  const n2 = n ** 2;
  console.log(n2);
  if (n2 > 30) {
    break;
  }
}

规范

Specification
Iterator Helpers
# sec-iteratorprototype.map

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看