Iterator.prototype.filter()

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

Iterator 实例的 filter() 方法返回一个新的 迭代器助手,该新 迭代器助手 仅生成所提供的回调函数返回 true 的迭代器元素。

¥The filter() method of Iterator instances returns a new iterator helper that yields only those elements of the iterator for which the provided callback function returns true.

语法

¥Syntax

js
filter(callbackFn)

参数

¥Parameters

callbackFn

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

element

当前正在处理的元素。

index

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

返回值

¥Return value

新的 迭代器助手。每次调用迭代器助手的 next() 方法时,它都会返回迭代器中回调函数返回 true 的下一个元素。当底层迭代器完成时,迭代器助手也完成(next() 方法生成 { value: undefined, done: true })。

¥A new iterator helper. Each time the iterator helper's next() method is called, it returns the next element in the iterator for which the callback function returns true. When the underlying iterator is completed, the iterator helper is also completed (the next() method produces { value: undefined, done: true }).

描述

¥Description

迭代器助手相对于数组方法的主要优点是它们能够使用无限迭代器。通过无限迭代器,filter() 允许你仅迭代那些满足给定条件的元素。

¥The main advantage of iterator helpers over array methods is their ability to work with infinite iterators. With infinite iterators, filter() allows you to iterate over only those elements that satisfy a given condition.

示例

¥Examples

使用过滤器()

¥Using filter()

以下示例创建一个迭代器,该迭代器生成斐波那契数列中的项,然后读取前几个偶数项:

¥The following example creates an iterator that yields terms in the Fibonacci sequence, and then reads the first few terms that are even:

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

const seq = fibonacci().filter((x) => x % 2 === 0);
console.log(seq.next().value); // 2
console.log(seq.next().value); // 8
console.log(seq.next().value); // 34

将 filter() 与 for...of 循环一起使用

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

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

¥filter() 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().filter((x) => x % 2 === 0)) {
  console.log(n);
  if (n > 30) {
    break;
  }
}

// Logs:
// 2
// 8
// 34

这相当于:

¥This is equivalent to:

js
for (const n of fibonacci()) {
  if (n % 2 !== 0) {
    continue;
  }
  console.log(n);
  if (n > 30) {
    break;
  }
}

规范

Specification
Iterator Helpers
# sec-iteratorprototype.filter

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看