Array.prototype.filter

Array.prototype.filter 是 JavaScript 中一个非常常用且强大的数组方法,它用于根据指定的条件过滤数组中的元素,并返回一个新数组,其中包含满足条件的元素。

基本语法

JavaScript
复制
array.filter(callback(element[, index[, array]])[, thisArg])
 
  • callback:一个函数,用于测试数组中的每个元素。如果返回 true,则该元素会被包含在返回的新数组中;如果返回 false,则不会被包含。
    • element:当前正在处理的数组元素。
    • index(可选):当前正在处理的数组元素的索引。
    • array(可选):调用 filter 的数组本身。
  • thisArg(可选):执行 callback 时使用的 this 值。
  • 返回值:一个新的数组,包含通过测试的所有元素。如果没有任何元素通过测试,则返回一个空数组。

示例

示例 1:筛选出数组中大于 10 的数字

JavaScript
复制
const numbers = [5, 12, 8, 130, 44];
const greaterThan10 = numbers.filter(num => num > 10);
console.log(greaterThan10); // 输出:[12, 130, 44]
 

示例 2:筛选出对象数组中符合条件的对象

JavaScript
复制
const users = [
    { id: 1, name: "Alice", age: 25 },
    { id: 2, name: "Bob", age: 30 },
    { id: 3, name: "Charlie", age: 22 }
];

const adults = users.filter(user => user.age >= 18);
console.log(adults); // 输出:[{ id: 1, name: "Alice", age: 25 }, { id: 2, name: "Bob", age: 30 }]
 

示例 3:使用索引参数

JavaScript
复制
const fruits = ["apple", "banana", "cherry", "date"];
const evenIndexFruits = fruits.filter((fruit, index) => index % 2 === 0);
console.log(evenIndexFruits); // 输出:["apple", "cherry"]
 

示例 4:使用 thisArg

JavaScript
复制
const fruits = ["apple", "banana", "cherry", "date"];
const minLen = 5;

const longFruits = fruits.filter(function(fruit) {
    return fruit.length >= this.minLen;
}, { minLen }); // 使用 thisArg 传递上下文

console.log(longFruits); // 输出:["banana", "cherry"]
 

注意事项

  1. 不修改原数组:
    • filter 方法不会修改原数组,它返回一个新数组。如果需要修改原数组,可以结合其他方法(如 splice)使用。
  2. 性能考虑:
    • 如果数组非常大,filter 方法可能会导致性能问题,因为它会对数组中的每个元素执行回调函数。在这种情况下,可以考虑优化回调函数的逻辑,或者使用更高效的数据结构(如 SetMap)。
  3. 回调函数返回值:
    • 回调函数的返回值必须是可以转换为布尔值的值。如果返回值为 true 或其他真值(如非零数字、非空字符串等),则当前元素会被包含在结果数组中;如果返回值为 false 或其他假值(如 0nullundefined 等),则不会被包含。
posted @ 2025-04-10 16:20  yinghualeihenmei  阅读(31)  评论(0)    收藏  举报