在 JavaScript 中,Array.filter() 方法用于创建一个包含通过特定条件的元素的新数组。它接受一个回调函数作为其参数,该函数对数组中的每个元素执行。如果回调函数返回 true,则将元素添加到新数组中,否则会将其筛选掉。
此方法不会更改或修改原始数组。此外,它不会对空元素执行回调函数。
语法
以下是 JavaScript 数组 filter() 方法的语法 -
array.filter(callbackFn (element, index, array), thisArg);
参数
此方法接受两个参数。下面描述相同 -
- callbackFn − 这是一个回调函数,将为数组中的每个元素调用一次。它进一步需要三个参数:
- element − 数组中正在处理的当前元素。
- index − 正在处理的当前元素的索引。
- array − 当前元素的数组。
- thisArg(可选)- 它指定传递给函数的值,用作其 this 值。
返回值
此方法返回一个新数组,其中包含回调函数返回 true 的元素。
示例 1
在以下示例中,提供的回调函数检查 “numbers” 数组中的每个元素,并返回一个新数组 “result”,其中包含所有大于 30 的元素。
<html>
<body>
<script>
const numbers = [10, 20, 30, 40, 50];
const result = numbers.filter(function (number) {
return number > 30;
});
document.write(result);
</script>
</body>
</html>
输出
40,50
示例 2
在这里,提供的回调函数检查数组中的每个元素是否都包含字母 'a' -
<html>
<body>
<script>
const animals = ['Lion', 'Cheetah', 'Tiger', 'Elephant', 'Dinosaur'];
const result = animals.filter(function (element) {
return element.includes('a');
});
document.write(result);
</script>
</body>
</html>
输出
Cheetah,Elephant,Dinosaur
示例 3
在此示例中,我们将检查每个年龄是否大于或等于 18 -
<html>
<body>
<script>
const ages = [18, 25, 13, 16, 22, 15];
const result = ages.filter(function (age) {
return age >= 18;
});
document.write(result);
</script>
</body>
</html>
输出
18,25,22