filter
filter用于对数组进行过滤。
它创建一个新数组,新数组中的元素是通过检查指定数组中符合条件的所有元素。
Array.prototype.filter = function (fn, context) {
if (typeof fn !== 'function') {
throw new TypeError(`${fn} is not a function`)
}
let arr = this
let result = []
for (let i = 0; i < arr.length; i++) {
let temp = fn.call(context, arr[i], i, arr)
if (temp) {
result.push(arr[i])
}
}
return result
}