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