在JavaScript数组操作中,筛选符合条件的数据是非常常见的需求,Array.prototype.filter作为内置的数组过滤方法,能够高效完成这类操作。下面我们来详细了解它的使用方法。

filter方法基本语法
filter是数组实例的方法,调用时不需要手动挂载,所有数组都可以直接调用。它的基本语法如下:
// 基本语法 const newArray = arr.filter(callback(element[, index[, array]])[, thisArg])
其中各个参数的含义如下:
- callback:必须参数,用来测试每个元素的函数,返回true表示保留该元素,返回false则剔除。它可以接收三个参数:
- element:当前正在处理的元素
- index(可选):当前元素的索引
- array(可选):调用filter的原数组
- thisArg(可选):执行callback时使用的this值
基础使用案例
筛选数字数组中的偶数
这是最基础的filter使用场景,筛选出数组中所有的偶数元素:
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; // 筛选偶数 const evenNumbers = numbers.filter(item => item % 2 === 0); console.log(evenNumbers); // 输出 [2, 4, 6, 8, 10] console.log(numbers); // 原数组不变,输出 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
筛选对象数组中的符合条件数据
实际开发中我们经常会处理对象数组,比如筛选年龄大于18岁的用户:
const users = [
{ name: '张三', age: 16 },
{ name: '李四', age: 20 },
{ name: '王五', age: 17 },
{ name: '赵六', age: 22 }
];
// 筛选成年用户
const adultUsers = users.filter(user => user.age >= 18);
console.log(adultUsers);
// 输出 [{ name: '李四', age: 20 }, { name: '赵六', age: 22 }]进阶使用技巧
使用index参数去重
结合index参数,我们可以用filter实现数组去重操作:
const arr = [1, 2, 2, 3, 3, 3, 4, 5, 5];
// 去重,只保留第一次出现的元素
const uniqueArr = arr.filter((item, index) => {
return arr.indexOf(item) === index;
});
console.log(uniqueArr); // 输出 [1, 2, 3, 4, 5]指定this指向
当callback是普通函数时,可以通过thisArg指定函数内部的this指向:
const filterCondition = {
min: 10,
max: 20
};
const nums = [5, 12, 18, 25, 8, 15];
// 筛选10到20之间的数字,指定this为filterCondition
const result = nums.filter(function(item) {
return item >= this.min && item <= this.max;
}, filterCondition);
console.log(result); // 输出 [12, 18, 15]常见注意事项
- filter不会改变原数组,总是返回一个新的数组,如果原数组为空,会返回空数组
- callback函数需要返回布尔值,如果返回的不是布尔值,会被隐式转换为布尔值,比如返回0会被当作false,非0数字会被当作true
- filter会遍历数组中的所有元素,即使前面的元素已经不符合条件,后面的元素依然会被处理
- 稀疏数组中的空位会被跳过,不会调用callback处理
注意:不要在filter的callback中修改原数组,虽然filter本身不会修改原数组,但如果在callback中手动修改,可能会导致不可预期的结果。
总结
Array.prototype.filter是JavaScript中非常实用的数组方法,适合用来筛选符合条件的数组元素,它的核心特点是不会修改原数组,返回新数组,使用起来简单清晰。只要掌握它的参数含义和基本使用逻辑,就能在各类数组筛选场景中灵活应用,提升代码的简洁性和可读性。
JavaScriptArrayfilter方法数组过滤修改时间:2026-05-29 23:02:26