filter函数如何使用
发布时间:09/01 来源:未知 浏览:
关键词:
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函数如何使用的具体内容,更多请关注百分百源码网其它相关文章!