javascript中的arr.filter()函数用于从给定数组创建一个新数组,该数组仅包含给定数组中满足参数函数设置条件的那些元素。下面我们就来具体看一下filter()的使用方法。

filter()的基本语法如下:
var newArray = arr.filter(arg_function[, this_arg])
filter()函数的参数是另一个函数,它定义要为数组的每个元素检查的条件。这个arg_function本身有三个参数:
array:这是调用.filter()函数的数组
index:这是函数处理的当前元素的索引。
element:这是函数正在处理的当前元素。
另一个参数this_arg用于表示函数在执行参数函数时使用此值。
下面我们来看具体的示例
函数filter()创建一个新数组,该数组仅包含满足isPositive()函数检查的条件的元素。
例1:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<script>
function isPositive(value) {
return value > 0;
}
function func() {
var filtered = [112, 52, 0, -1, 944].filter(isPositive);
document.write(filtered);
}
func();
</script>
</body>
</html>输出结果为:112,52,944
例2:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<script>
function isEven(value) {
return value%2 == 0;
}
function func() {
var filtered = [11, 98, 31, 23, 944].filter(isEven);
document.write(filtered);
}
func();
</script>
</body>
</html>输出结果为:98,944
本篇文章到这里就已经全部结束了,更多精彩内容大家可以关注php中文网的其他相关栏目教程!!!
以上就是filter函数怎么使用的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号