网站推广.NET

网站推广.NET

filter函数怎么使用

来源:互联网

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

本篇文章到这里就已经全部结束了,更多精彩内容大家可以关注本站的其他相关栏目教程!!!

标签: filter函数