JavaScript - 数组 filter() 方法
在 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

