Iterator.prototype.every()

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

Iterator 实例的 every() 方法与 Array.prototype.every() 类似:它测试迭代器生成的所有元素是否通过所提供函数实现的测试。它返回一个布尔值。

¥The every() method of Iterator instances is similar to Array.prototype.every(): it tests whether all elements produced by the iterator pass the test implemented by the provided function. It returns a boolean value.

语法

¥Syntax

js
every(callbackFn)

参数

¥Parameters

callbackFn

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

element

当前正在处理的元素。

index

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

返回值

¥Return value

如果 callbackFn 为每个元素返回 truthy 值,则为 true。否则,false

¥true if callbackFn returns a truthy value for every element. Otherwise, false.

描述

¥Description

every() 迭代迭代器并为每个元素调用一次 callbackFn 函数。如果回调函数返回一个假值,它会立即返回 false。否则,它将迭代直到迭代器末尾并返回 true。如果 every() 返回 false,则通过调用其 return() 方法来关闭底层迭代器。

¥every() iterates the iterator and invokes the callbackFn function once for each element. It returns false immediately if the callback function returns a falsy value. Otherwise, it iterates until the end of the iterator and returns true. If every() returns false, the underlying iterator is closed by calling its return() method.

迭代器助手相对于数组方法的主要优点是它们能够使用无限迭代器。对于无限迭代器,一旦找到第一个假值,every() 就会返回 false。如果 callbackFn 始终返回真值,则该方法永远不会返回。

¥The main advantage of iterator helpers over array methods is their ability to work with infinite iterators. With infinite iterators, every() returns false as soon as the first falsy value is found. If the callbackFn always returns a truthy value, the method never returns.

示例

¥Examples

使用每个()

¥Using every()

js
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().every(isEven)); // false

const isPositive = (x) => x > 0;
console.log(fibonacci().take(10).every(isPositive)); // true
console.log(fibonacci().every(isPositive)); // Never completes

调用 every() 总是会关闭底层迭代器,即使该方法提前返回。迭代器永远不会处于中途状态。

¥Calling every() always closes the underlying iterator, even if the method early-returns. The iterator is never left in a half-way state.

js
const seq = fibonacci();
console.log(seq.every(isEven)); // false
console.log(seq.next()); // { value: undefined, done: true }

规范

Specification
Iterator Helpers
# sec-iteratorprototype.every

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看