Array.prototype.filter()
Array
实例的 filter()
方法创建给定数组的一部分的 浅拷贝,筛选出给定数组中通过所提供函数实现的测试的元素。
¥The filter()
method of Array
instances creates a shallow copy of a portion of a given array, filtered down to just the elements from the given array that pass the test implemented by the provided function.
Try it
语法
参数
返回值
¥Return value
给定数组的 浅拷贝 仅包含通过测试的元素。如果没有元素通过测试,则返回空数组。
¥A shallow copy of the given array containing just the elements that pass the test. If no elements pass the test, an empty array is returned.
描述
¥Description
filter()
方法是 迭代法 方法。它为数组中的每个元素调用一次提供的 callbackFn
函数,并构造一个由 callbackFn
返回 truthy 值的所有值组成的新数组。未通过 callbackFn
测试的数组元素不包含在新数组中。请阅读 迭代法 部分,了解有关这些方法一般如何工作的更多信息。
¥The filter()
method is an iterative method. It calls a provided callbackFn
function once for each element in an array, and constructs a new array of all the values for which callbackFn
returns a truthy value. Array elements which do not pass the callbackFn
test are not included in the new array. Read the iterative methods section for more information about how these methods work in general.
callbackFn
仅针对已赋值的数组索引调用。稀疏数组 中的空槽不会调用它。
¥callbackFn
is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays.
filter()
方法是 generic。它只期望 this
值具有 length
属性和整数键控属性。
¥The filter()
method is generic. It only expects the this
value to have a length
property and integer-keyed properties.
示例
过滤掉所有小值
¥Filtering out all small values
以下示例使用 filter()
创建一个过滤数组,其中删除了所有值小于 10 的元素。
¥The following example uses filter()
to create a filtered array that has all elements with values less than 10 removed.
function isBigEnough(value) {
return value >= 10;
}
const filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
// filtered is [12, 130, 44]
查找数组中的所有素数
¥Find all prime numbers in an array
以下示例返回数组中的所有素数:
¥The following example returns all prime numbers in the array:
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 中过滤无效条目
¥Filtering invalid entries from JSON
以下示例使用 filter()
创建包含非零数字 id
的所有元素的筛选 JSON。
¥The following example uses filter()
to create a filtered JSON of all elements with non-zero, numeric 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
在数组中搜索
¥Searching in array
以下示例使用 filter()
根据搜索条件过滤数组内容。
¥Following example uses filter()
to filter array content based on search criteria.
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 的第三个参数
¥Using the third argument of callbackFn
如果你想访问数组中的另一个元素,特别是当你没有引用该数组的现有变量时,array
参数非常有用。以下示例首先使用 map()
从每个名称中提取数字 ID,然后使用 filter()
选择大于其邻居的名称。
¥The array
argument is useful if you want to access another element in the array, especially when you don't have an existing variable that refers to the array. The following example first uses map()
to extract the numerical ID from each name and then uses filter()
to select the ones that are greater than its neighbors.
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
参数不是正在构建的数组 - 无法从回调函数访问正在构建的数组。
¥The array
argument is not the array that is being built — there is no way to access the array being built from the callback function.
在稀疏数组上使用 filter()
对非数组对象调用 filter()
¥Calling filter() on non-array objects
filter()
方法读取 this
的 length
属性,然后访问键为小于 length
的非负整数的每个属性。
¥The filter()
method reads the length
property of this
and then accesses each property whose key is a nonnegative integer less than 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' ]
规范
Specification |
---|
ECMAScript Language Specification # sec-array.prototype.filter |
浏览器兼容性
BCD tables only load in the browser