JavaScript array.filter()方法满足条件的所有元素集合,返回一个新数组。
array.filter(callback[, thisObject]);
callback - 用于测试数组的每个元素。
链接:https://www.learnfk.comhttps://www.learnfk.com/javascript/array-filter.html
来源:LearnFk无涯教程网
thisObject - 要在执行回调时用作的对象。
返回创建的数组。
此方法是ECMA-262标准的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; }; }
<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
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)
HarmonyOS快速入门与实战 -〔QCon+案例研习社〕
Tony Bai · Go语言第一课 -〔Tony Bai〕