扫码一下
查看教程更方便
filter()方法创建一个新数组,其中包含通过提供的函数实现的测试的所有元素。
注意: filter() 不会对空数组进行检测。
注意: filter() 不会改变原始数组。
语法如下
array.filter(callback[, thisobject]);
返回数组,包含了符合条件的所有元素。如果没有符合条件的元素则返回空数组。
所有主流浏览器都支持 filter() 方法。
此方法是 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;
};
}
javascript array filter method
输出结果
filtered value : 12,130,44