TypedArray.prototype.find()

TypedArray 实例的 find() 方法返回所提供的类型化数组中满足所提供的测试函数的第一个元素。如果没有值满足测试函数,则返回 undefined。该方法与 Array.prototype.find() 的算法相同。

¥The find() method of TypedArray instances returns the first element in the provided typed array that satisfies the provided testing function. If no values satisfy the testing function, undefined is returned. This method has the same algorithm as Array.prototype.find().

Try it

语法

¥Syntax

js
find(callbackFn)
find(callbackFn, thisArg)

参数

¥Parameters

callbackFn

对类型化数组中的每个元素执行的函数。它应该返回 truthy 值以指示已找到匹配元素,否则返回 falsy 值。使用以下参数调用该函数:

element

类型化数组中正在处理的当前元素。

index

类型化数组中当前正在处理的元素的索引。

array

调用了类型化数组 find()

thisArg Optional

执行 callbackFn 时用作 this 的值。参见 迭代法

返回值

¥Return value

类型化数组中满足所提供的测试函数的第一个元素。否则,返回 undefined

¥The first element in the typed array that satisfies the provided testing function. Otherwise, undefined is returned.

描述

¥Description

详细信息请参见 Array.prototype.find()。此方法不是通用的,只能在类型化数组实例上调用。

¥See Array.prototype.find() for more details. This method is not generic and can only be called on typed array instances.

示例

¥Examples

在类型化数组中查找素数

¥Find a prime number in a typed array

以下示例在类型化数组中查找素数元素(如果不存在素数则返回 undefined)。

¥The following example finds an element in the typed array that is a prime number (or returns undefined if there is no prime number).

js
function isPrime(element, index, array) {
  let start = 2;
  while (start <= Math.sqrt(element)) {
    if (element % start++ < 1) {
      return false;
    }
  }
  return element > 1;
}

const uint8 = new Uint8Array([4, 5, 8, 12]);
console.log(uint8.find(isPrime)); // 5

规范

Specification
ECMAScript Language Specification
# sec-%typedarray%.prototype.find

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看