一、Filter函数的介绍
在JavaScript中,数组是一个非常重要的数据类型,属于对象的一种。在实际的开发过程中,我们往往需要对数组进行筛选、过滤等操作,这时候就可以使用JavaScript中的filter
函数。
filter
函数是JavaScript中一个很实用的函数,它可以筛选出符合指定条件的数组元素,然后将这些元素组成一个新的数组返回,不影响原来的数组。filter
函数的语法如下:
array.filter(function(currentValue,index,arr), thisValue)
其中,参数currentValue
表示数组中正在处理的当前元素,index
表示当前元素的索引值,arr
表示当前数组;而thisValue
则可选,表示传递给函数的额外值,这个值在函数中使用。
二、Filter函数的基本使用
为了更好的理解filter
函数,接下来我们将结合代码进行详细的讲解。首先,我们定义一个数组:
const arr = [1,2,3,4,5,6,7,8,9];
现在,我们来使用filter
函数将这个数组中大于等于5的数筛选出来,并形成一个新的数组:
const result = arr.filter(function(item){
return item >= 5;
});
console.log(result); // [5,6,7,8,9]
我们还可以使用箭头函数进行简写:
const result = arr.filter(item => item >= 5);
console.log(result); // [5,6,7,8,9]
三、Filter函数进阶使用
1. 字符串的筛选
在使用filter
函数中,我们不仅可以对数字进行筛选,还可以对字符串进行筛选。比如下面这个例子,我们来对一个字符串数组进行筛选,只要包含字母e的字符串:
const strArr = ['hello', 'world', 'apple', 'pear', 'peach'];
const result = strArr.filter(function(item){
return item.indexOf('e') >= 0;
});
console.log(result); // ["hello", "pear", "peach"]
2. 对象的筛选
除了对数组和字符串进行筛选,我们还可以对对象进行筛选。比如下面这个例子,我们有一个存储人员信息的数组,我们来筛选出工资大于等于5000的人员:
const staff = [
{name: 'Bob', salary: 4000},
{name: 'Alice', salary: 6000},
{name: 'John', salary: 5000},
{name: 'Tom', salary: 7000}
];
const result = staff.filter(function(item){
return item.salary >= 5000;
});
console.log(result); // [{name: 'Alice', salary: 6000},{name: 'John', salary: 5000},{name: 'Tom', salary: 7000}]
3. 复杂条件筛选
除了基本的条件筛选,我们还可以使用filter
函数进行更加复杂的筛选操作。比如下面这个例子,我们要将一个数值数组按照奇数和偶数分别存储到两个数组中:
const arr = [1,2,3,4,5,6,7,8,9];
const result = {
odd:[],
even:[]
};
arr.filter(function(item){
if(item%2 === 0){
result.even.push(item);
}else{
result.odd.push(item);
}
});
console.log(result); // {odd: [1, 3, 5, 7, 9], even: [2, 4, 6, 8]}
四、总结
通过本文的介绍和实例演示,我们了解了JavaScript中的filter
函数的基本语法和用法,并能够熟练的运用到我们的开发工作中。同时,我们也发现filter
函数不仅可以应用于数组筛选上,还可以应用到字符串和对象等其他数据类型上,功能非常强大。