手写 filter
文章目录
手写 filter
filter()方法创建一个新数组, 其包含通过所提供函数实现的测试的所有元素。
filter 不会改变原数组,它返回过滤后的新数组
var newArray = arr.filter(callback(element[, index[, array]])[, thisArg])
-
callback
用来测试数组的每个元素的函数。返回 true 表示该元素通过测试,保留该元素,false 则不保留。它接受以下三个参数:- element
数组中当前正在处理的元素。 - index 可选
正在处理的元素在数组中的索引。 - array 可选
调用了 filter 的数组本身。 - thisArg 可选
执行 callback 时,用于 this 的值。
- element
Array.prototype.filter = function(fn, thisArg) {
var _this;
if (typeof fn !== "function") {
throw "参数必须为函数";
}
//get array going to be iterated
let arr = this;
if (!Array.isArray(arr)) {
throw "只能对数组使用forEach方法";
}
if (arguments.length > 1) {
_this = thisArg;
}
let result = [];
for (let index = 0; index < arr.length; index++) {
let invokedReturn = fn.call(_this, arr[index], index, arr);
if (invokedReturn) {
result.push(arr[index]);
}
}
return result;
};
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论