js数组高阶函数——filter()方法

filter()方法

⭐一般来说,filter() 方法用于过滤数组中的元素,并返回一个新数组。
语法:

array.filter(function(value, index, arr), thisValue)

参数说明:

  • function:函数,规定了过滤条件。必需。该函数接受三个参数:当前元素的值、当前元素的索引和包含该元素的数组。
  • thisValue:可选项。对象作为该执行回调时使用,传递给函数,用作 “this” 的值。如果省略thisValue,则默认是全局对象(浏览器环境下是 window 对象)。

返回值:
返回一个新数组,其中包含符合条件的元素。以下会举5个例子,看懂例子,基本就掌握了。

-------------------------------------------------------------⭐------------------------------------------------------------------

⭐⭐⭐例1

假设我们有一个数字数组,现在想要过滤出其中所有大于等于5的数字:

let numbers = [1, 2, 3, 4, 5, 6, 7, 8];
let result = numbers.filter(function(num) {
    
    
    return num >= 5;
});
console.log(result);   // 输出:[5, 6, 7, 8]

上述代码中使用匿名函数定义了过滤条件,并将其作为第一个参数传递给 filter() 方法。最终结果保存在变量 result 中,并输出到控制台中。
-------------------------------------------------------------⭐------------------------------------------------------------------

⭐⭐⭐例2

				let arr = [{
    
    
					id: 1,
					name: '神墓'
				}, {
    
    
					id: 2,
					name: '完美世界'
				}, {
    
    
					id: 1,
					name: '长生界'
				}, {
    
    
					id: 7,
					name: '遮天'
				}, {
    
    
					id: 1,
					name: '不死不灭'
				}]
				console.log(arr.filter(item => item.id == 1));
				

打印结果:
在这里插入图片描述

上面这个例子,我们将数组中每一项id为1的筛选出来。后端有SQL语句可以查询,前端也可以通过这样的方式来实现查询,筛选。

也有别的写法,数组不变:

			let fe = arr.filter((item)=function (){
    
    
				return (item.id ==1 )
			})
			console.log(fe);

这样写,和上面打印的结果一模一样。
-------------------------------------------------------------⭐------------------------------------------------------------------

⭐⭐⭐例3

			const words = ['赏', '花', '赏', '月', '赏', '秋','香'];
			const result = words.filter(word => word != '赏');
			console.log(result);

在这里插入图片描述上面例子中,我们挑出了数组words中不是赏字的所有字

-------------------------------------------------------------⭐------------------------------------------------------------------

⭐⭐⭐例4

const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
const result = words.filter(word => word.length > 6);
console.log(result);

在这里插入图片描述上面的例子中,我们筛选words数组中的每一项元素的长度大于6的元素,因为每一个元素都是个单词,是个字符串,字符串也有长度,所以这样也可以过滤出我们想要的。

-------------------------------------------------------------⭐------------------------------------------------------------------

⭐⭐⭐例5

			function isBigEnoughcount(value) {
    
    
				return value >= 10;
			}
			const filtered = [12, 5, 8, 130, 44].filter(isBigEnoughcount);
			console.log(filtered);

在这里插入图片描述
这个例子中,声明一个数组,并过滤,执行的逻辑是一个条件。条件为值大于等于10,也就是说,我们声明了一个数组,并且筛选了数组中每一项大于10的数字。


猜你喜欢

转载自blog.csdn.net/dyk11111/article/details/131242109
今日推荐