JS filter函数
在JavaScript中,filter()
函数是数组对象的一个原生方法,它用于过滤数组中的元素。通过传入一个回调函数作为参数,filter()
函数会对数组中的每一个元素调用该回调函数,返回值为true的元素会被保留在新数组中,而返回值为false的元素会被过滤掉。
语法
array.filter(function(currentValue, index, arr), thisValue)
function(currentValue, index, arr)
: 回调函数,接收三个参数currentValue
: 当前元素的值index
: 当前元素的索引arr
: 当前数组
thisValue
: 回调函数中的this对象
示例
// 过滤数组中的偶数
const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers); // [2, 4]
// 过滤数组中的字符串
const mixedArray = [1, 'hello', true, 'world', 42];
const stringsOnly = mixedArray.filter(item => typeof item === 'string');
console.log(stringsOnly); // ['hello', 'world']
// 过滤数组中大于等于10的数字
const scores = [65, 82, 97, 45, 30];
const highScores = scores.filter(score => score >= 70);
console.log(highScores); // [82, 97]
在上面的示例中,我们对不同类型的数组进行了过滤操作,可以看到filter()
函数对数组元素的筛选操作非常方便。
返回值
filter()
函数返回一个新数组,包含回调函数返回true的元素。原始数组不会被改变。
注意事项
filter()
函数不会改变原始数组,它会返回一个新的数组。- 回调函数中返回值为布尔值,true则保留,false则过滤。
- 如果不需要对原始数组进行保留操作,可使用
forEach()
或map()
。
应用场景
filter()
函数在实际开发中有广泛的应用场景,例如:
- 过滤不符合条件的数据
- 在搜索功能中对列表进行过滤
- 处理用户输入,过滤敏感词汇
- 根据条件筛选商品列表等
总的来说,filter()
函数是一个非常灵活和方便的数组方法,在处理数据时可以大大提高开发效率和代码质量。