Array.prototype.filter()
试一试
const words = ["spray", "elite", "exuberant", "destruction", "present"];
const result = words.filter((word) => word.length > 6);
console.log(result);
// Expected output: Array ["exuberant", "destruction", "present"]
语法
filter(callbackFn)
filter(callbackFn, thisArg)
参数
callbackFn-
一个用于在数组的每个元素上执行的函数。它应该返回一个 truthy 值以保留该元素在结果数组中,否则返回一个 falsy 值。该函数将使用以下参数调用:
thisArg可选-
在执行
callbackFn时用作this的值。请参阅 迭代方法。
返回值
一个给定数组的 浅拷贝,其中只包含通过测试的元素。如果没有元素通过测试,则返回一个空数组。
描述
filter() 方法是一个 迭代方法。它为数组中的每个元素调用一次提供的 callbackFn 函数,并构造一个新数组,其中包含所有 callbackFn 返回 truthy 值的所有值。未通过 callbackFn 测试的数组元素将不包含在新数组中。有关这些方法通常如何工作的更多信息,请阅读 迭代方法 部分。
callbackFn 仅对具有已赋值的数组索引调用。对于稀疏数组中的空槽,它不会被调用。
filter() 方法是 通用的。它只期望 this 值具有 length 属性和整数键属性。
示例
过滤掉所有小值
以下示例使用 filter() 创建一个过滤后的数组,其中删除了所有值小于 10 的元素。
function isBigEnough(value) {
return value >= 10;
}
const filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
// filtered is [12, 130, 44]
在一个数组中查找所有素数
以下示例返回数组中的所有素数
const array = [-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
function isPrime(n) {
if (n < 2) {
return false;
}
if (n % 2 === 0) {
return n === 2;
}
for (let factor = 3; factor * factor <= n; factor += 2) {
if (n % factor === 0) {
return false;
}
}
return true;
}
console.log(array.filter(isPrime)); // [2, 3, 5, 7, 11, 13]
注意:isPrime() 实现仅用于演示。对于实际应用,您需要使用高度记忆化的算法,例如埃拉托斯特尼筛法,以避免重复计算。
过滤掉 JSON 中的无效条目
以下示例使用 filter() 创建一个过滤后的 JSON,其中包含所有 id 非零且为数字的元素。
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() 根据搜索条件过滤数组内容。
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。
const names = ["JC63", "Bob132", "Ursula89", "Ben96"];
const greatIDs = names
.map((name) => parseInt(name.match(/\d+/)[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() 会跳过空槽。
console.log([1, , undefined].filter((x) => x === undefined)); // [undefined]
console.log([1, , undefined].filter((x) => x !== 2)); // [1, undefined]
在非数组对象上调用 filter()
filter() 方法读取 this 的 length 属性,然后访问小于 length 的非负整数键的每个属性。
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® 2026 语言规范 # sec-array.prototype.filter |
浏览器兼容性
加载中…