JavaScript 中的 filter()

在 JavaScript 中,filter() 方法是用于过滤数组中的元素的高阶函数。filter() 方法将一个数组中的每个元素传递给一个回调函数,回调函数返回一个布尔值,决定该元素是否应该被过滤出数组。最终,filter() 方法返回一个新的数组,其中包含回调函数返回 true 的元素。

filter() 方法的基本语法如下:

array.filter(callback(element[, index[, array]])[, thisArg])


其中:

array:要过滤的数组。

callback:回调函数,接受以下参数:

        element:当前被遍历到的数组元素。

        index(可选):当前元素在数组中的索引。

        array(可选):被遍历的数组。

thisArg(可选):在回调函数中 this 关键字的值。

语法上可大致分为三类,如下:

// 箭头函数
filter((element) => { /* … */ } )
filter((element, index) => { /* … */ } )
filter((element, index, array) => { /* … */ } )

// 回调函数
filter(callbackFn)
filter(callbackFn, thisArg)

// 内联回调函数
filter(function(element) { /* … */ })
filter(function(element, index) { /* … */ })
filter(function(element, index, array){ /* … */ })
filter(function(element, index, array) { /* … */ }, thisArg)


filter() 方法在遍历数组时,对每个元素都调用回调函数。如果回调函数返回 true,则该元素将被包含在新数组中;如果返回 false,则该元素将被过滤掉。

例如,下面的代码演示了如何使用 filter() 方法过滤出一个数组中的偶数:

const numbers = [1, 2, 3, 4, 5, 6];
const evenNumbers = numbers.filter((number) => number % 2 === 0);
console.log(evenNumbers); // [2, 4, 6]


在这个例子中,回调函数 (number) => number % 2 === 0 用于过滤出数组中的偶数,最终返回一个新数组 [2, 4, 6]。

除了基本语法之外,filter() 方法还可以有一些高级用法

例如:使用第二个参数指定回调函数的 this 值。

const fruits = ["apple", "banana", "orange"];
const filteredFruits = fruits.filter(function(fruit) {
  return fruit === this;
}, "apple");
console.log(filteredFruits); // ["apple"]


在这个例子中,回调函数中的 this 关键字被设置为字符串 "apple",filter() 方法只会过滤出值等于 "apple" 的元素。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值