在 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" 的元素。
filter()方法是JavaScript中用于过滤数组元素的高阶函数,它根据回调函数返回的布尔值决定元素去留。回调函数可以接受element(当前元素)、index(索引)和array(原数组)作为参数,thisArg可指定回调函数的上下文。示例展示了如何过滤出偶数和基于特定值过滤数组。
1880

被折叠的 条评论
为什么被折叠?



