Array.prototype.filter()

基线 广泛可用

此功能已得到充分确立,并且可以在许多设备和浏览器版本上运行。它自以下时间起在所有浏览器中都可用 2015 年 7 月.

filter() 方法是 Array 实例的方法,它会创建给定数组一部分的 浅拷贝,并将其过滤为仅包含来自给定数组中通过提供的函数实现的测试的元素。

试一试

语法

js
filter(callbackFn)
filter(callbackFn, thisArg)

参数

callbackFn

对数组中的每个元素执行的函数。它应该返回一个 真值 以将元素保留在结果数组中,否则返回一个 假值。该函数使用以下参数调用

元素

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

索引

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

数组

调用 filter() 的数组。

thisArg 可选

在执行 callbackFn 时用作 this 的值。请参阅 迭代方法

返回值

给定数组的 浅拷贝,其中仅包含通过测试的元素。如果没有任何元素通过测试,则返回一个空数组。

描述

filter() 方法是 迭代方法。它会对数组中的每个元素调用一次提供的 callbackFn 函数,并构造一个新数组,其中包含 callbackFn 返回 真值 的所有值。未通过 callbackFn 测试的数组元素不会包含在新数组中。阅读 迭代方法 部分,以获取有关这些方法如何普遍工作的更多信息。

callbackFn 仅对已分配值的数组索引调用。它不会对 稀疏数组 中的空插槽调用。

filter() 方法是 泛型 的。它只期望 this 值具有 length 属性和整数键属性。

示例

过滤掉所有小值

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

js
function isBigEnough(value) {
  return value >= 10;
}

const filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
// filtered is [12, 130, 44]

查找数组中的所有素数

以下示例返回数组中的所有素数

js
const array = [-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];

function isPrime(num) {
  for (let i = 2; num > i; i++) {
    if (num % i === 0) {
      return false;
    }
  }
  return num > 1;
}

console.log(array.filter(isPrime)); // [2, 3, 5, 7, 11, 13]

过滤 JSON 中的无效条目

以下示例使用 filter() 创建一个过滤后的 JSON,其中包含所有具有非零数值 id 的元素。

js
const arr = [
  { id: 15 },
  { id: -1 },
  { id: 0 },
  { id: 3 },
  { id: 12.2 },
  {},
  { id: null },
  { id: NaN },
  { id: "undefined" },
];

let invalidEntries = 0;

function filterByID(item) {
  if (Number.isFinite(item.id) && item.id !== 0) {
    return true;
  }
  invalidEntries++;
  return false;
}

const arrByID = arr.filter(filterByID);

console.log("Filtered Array\n", arrByID);
// Filtered Array
// [{ id: 15 }, { id: -1 }, { id: 3 }, { id: 12.2 }]

console.log("Number of Invalid Entries =", invalidEntries);
// Number of Invalid Entries = 5

在数组中搜索

以下示例使用 filter() 根据搜索条件过滤数组内容。

js
const fruits = ["apple", "banana", "grapes", "mango", "orange"];

/**
 * Filter array items based on search criteria (query)
 */
function filterItems(arr, query) {
  return arr.filter((el) => el.toLowerCase().includes(query.toLowerCase()));
}

console.log(filterItems(fruits, "ap")); // ['apple', 'grapes']
console.log(filterItems(fruits, "an")); // ['banana', 'mango', 'orange']

使用 callbackFn 的第三个参数

如果您想访问数组中的另一个元素,则 array 参数很有用,尤其是在您没有引用该数组的现有变量时。以下示例首先使用 map() 从每个名称中提取数值 ID,然后使用 filter() 选择大于其相邻元素的 ID。

js
const names = ["JC63", "Bob132", "Ursula89", "Ben96"];
const greatIDs = names
  .map((name) => parseInt(name.match(/[0-9]+/)[0], 10))
  .filter((id, idx, arr) => {
    // Without the arr argument, there's no way to easily access the
    // intermediate array without saving it to a variable.
    if (idx > 0 && id <= arr[idx - 1]) return false;
    if (idx < arr.length - 1 && id <= arr[idx + 1]) return false;
    return true;
  });
console.log(greatIDs); // [132, 96]

array 参数不是正在构建的数组——无法从回调函数中访问正在构建的数组。

在稀疏数组上使用 filter()

filter() 将跳过空插槽。

js
console.log([1, , undefined].filter((x) => x === undefined)); // [undefined]
console.log([1, , undefined].filter((x) => x !== 2)); // [1, undefined]

在非数组对象上调用 filter()

filter() 方法读取 thislength 属性,然后访问其键为小于 length 的非负整数的每个属性。

js
const arrayLike = {
  length: 3,
  0: "a",
  1: "b",
  2: "c",
  3: "a", // ignored by filter() since length is 3
};
console.log(Array.prototype.filter.call(arrayLike, (x) => x <= "b"));
// [ 'a', 'b' ]

规范

规范
ECMAScript 语言规范
# sec-array.prototype.filter

浏览器兼容性

BCD 表格仅在启用了 JavaScript 的浏览器中加载。

另请参阅