JavaScript数组过filter()方法创建一个新的数组提供的函数来实现测试的所有元素。
语法
array.filter(callback[, thisObject])
下面是参数的详细信息:
-
callback%uA0: 函数用来测试数组的每个元素
-
thisObject%uA0: 对象作为该执行回调时使用
返回值:
返回所创建数组
兼容性:
这种方法是一个JavaScript扩展到ECMA-262标准因此它可能不存在在标准的其他实现。为了使它工作,你需要添加下面的脚本的顶部代码:
if (!Array.prototype.filter) { Array.prototype.filter = function(fun /*, thisp*/) { var len = this.length if (typeof fun != "function") throw new TypeError() var res = new Array() var thisp = arguments[1] for (var i = 0 i < len i++) { if (i in this) { var val = this[i] // in case fun mutates this if (fun.call(thisp, val, i, this)) res.push(val) } } return res } }
例子:
<html> <head> <title>JavaScript Array filter Method</title> </head> <body> <script type="text/javascript"> if (!Array.prototype.filter) { Array.prototype.filter = function(fun /*, thisp*/) { var len = this.length if (typeof fun != "function") throw new TypeError() var res = new Array() var thisp = arguments[1] for (var i = 0 i < len i++) { if (i in this) { var val = this[i] // in case fun mutates this if (fun.call(thisp, val, i, this)) res.push(val) } } return res } } function isBigEnough(element, index, array) { return (element >= 10) } var filtered = [12, 5, 8, 130, 44].filter(isBigEnough) document.write("Filtered Value : " + filtered ) </script> </body> </html>
这将产生以下结果:
Filtered Value : 12,130,44
%uA0