📅  最后修改于: 2023-12-03 15:01:43.828000             🧑  作者: Mango
JavaScript 中,数组可以通过 filter() 方法进行筛选过滤,返回一个新数组,新数组中只包含符合条件的元素。该方法接受一个回调函数作为参数,用于判断每一个元素是否符合条件,回调函数返回值为 true 或 false,true 表示该元素被筛选,false 表示该元素不被筛选。
arr.filter(callback[, thisArg])
arr
:要进行筛选的数组,必选。callback
:用于筛选过滤的回调函数,必选。thisArg
:可选,回调函数执行时 this 对象指向。回调函数支持三个参数:
element
:当前元素的值。index
:当前元素的索引。array
:原始数组。const arr = [1, 2, 3, 4, 5];
const result = arr.filter((element) => element % 2 === 0);
console.log(result); // [2, 4]
const arr = [1, 5, 10, 15, 20];
const result = arr.filter((element) => element > 10);
console.log(result); // [15, 20]
const arr = ["apple", "banana", "grape", "peach"];
const result = arr.filter((element) => element.length >= 5);
console.log(result); // ["apple", "banana", "grape"]
const arr = [
{ name: "apple", price: 10 },
{ name: "banana", price: 20 },
{ name: "grape", price: 8 },
{ name: "peach", price: 15 },
];
const result = arr.filter((element) => element.price > 10);
console.log(result); // [{ name: "banana", price: 20 }, { name: "peach", price: 15 }]
const arr = [1, 2, 3, 4, 5];
const result = arr.filter(function (element) {
return element > this;
}, 2);
console.log(result); // [3, 4, 5]