Iterator.prototype.find()
Experimental: This is an experimental technology
Check the Browser compatibility table carefully before using this in production.
Iterator
实例的 find()
方法与 Array.prototype.find()
类似:它返回迭代器生成的满足所提供的测试函数的第一个元素。如果没有值满足测试函数,则返回 undefined
。
¥The find()
method of Iterator
instances is similar to Array.prototype.find()
: it returns the first element produced by the iterator that satisfies the provided testing function. If no values satisfy the testing function, undefined
is returned.
语法
参数
¥Parameters
callbackFn
-
对迭代器生成的每个元素执行的函数。它应该返回 truthy 值以指示已找到匹配元素,否则返回 falsy 值。使用以下参数调用该函数:
返回值
描述
¥Description
find()
迭代迭代器并为每个元素调用一次 callbackFn
函数。如果回调函数返回真值,它会立即返回该元素。否则,它将迭代直到迭代器末尾并返回 undefined
。如果 find()
返回一个元素,则通过调用其 return()
方法来关闭底层迭代器。
¥find()
iterates the iterator and invokes the callbackFn
function once for each element. It returns the element immediately if the callback function returns a truthy value. Otherwise, it iterates until the end of the iterator and returns undefined
. If find()
returns an element, the underlying iterator is closed by calling its return()
method.
迭代器助手相对于数组方法的主要优点是它们能够使用无限迭代器。对于无限迭代器,find()
一旦找到第一个满足的元素就返回它。如果 callbackFn
始终返回假值,则该方法永远不会返回。
¥The main advantage of iterator helpers over array methods is their ability to work with infinite iterators. With infinite iterators, find()
returns the first satisfying element as soon as it is found. If the callbackFn
always returns a falsy value, the method never returns.
示例
使用 find()
¥Using find()
function* fibonacci() {
let current = 1;
let next = 1;
while (true) {
yield current;
[current, next] = [next, current + next];
}
}
const isEven = (x) => x % 2 === 0;
console.log(fibonacci().find(isEven)); // 2
const isNegative = (x) => x < 0;
console.log(fibonacci().take(10).find(isNegative)); // undefined
console.log(fibonacci().find(isNegative)); // Never completes
调用 find()
总是会关闭底层迭代器,即使该方法提前返回。迭代器永远不会处于中途状态。
¥Calling find()
always closes the underlying iterator, even if the method early-returns. The iterator is never left in a half-way state.
const seq = fibonacci();
console.log(seq.find(isEven)); // 2
console.log(seq.next()); // { value: undefined, done: true }
规范
Specification |
---|
Iterator Helpers # sec-iteratorprototype.find |
浏览器兼容性
BCD tables only load in the browser