TypedArray.prototype.filter()

TypedArray 实例的 filter() 方法创建给定类型化数组的一部分的副本,过滤为仅给定类型化数组中通过所提供函数实现的测试的元素。该方法与 Array.prototype.filter() 的算法相同。

¥The filter() method of TypedArray instances creates a copy of a portion of a given typed array, filtered down to just the elements from the given typed array that pass the test implemented by the provided function. This method has the same algorithm as Array.prototype.filter().

Try it

语法

¥Syntax

js
filter(callbackFn)
filter(callbackFn, thisArg)

参数

¥Parameters

callbackFn

对类型化数组中的每个元素执行的函数。它应该返回 truthy 值以将元素保留在结果类型化数组中,否则返回 falsy 值。使用以下参数调用该函数:

element

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

index

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

array

调用了类型化数组 filter()

thisArg Optional

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

返回值

¥Return value

给定类型化数组的副本,仅包含通过测试的元素。如果没有元素通过测试,则返回一个空类型数组。

¥A copy of the given typed array containing just the elements that pass the test. If no elements pass the test, an empty typed array is returned.

描述

¥Description

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

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

示例

¥Examples

过滤掉所有小值

¥Filtering out all small values

以下示例使用 filter() 创建一个过滤类型数组,其中删除了所有值小于 10 的元素。

¥The following example uses filter() to create a filtered typed array that has all elements with values less than 10 removed.

js
function isBigEnough(element, index, array) {
  return element >= 10;
}
new Uint8Array([12, 5, 8, 130, 44]).filter(isBigEnough);
// Uint8Array [ 12, 130, 44 ]

规范

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

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看