// ES5循环循环实现filter
const selfFilter = function (fn, context) { let arr = Array.prototype.slice.call(this) let filteredArr = [] for (let i = 0; i < arr.length; i++) { if(!arr.hasOwnProperty(i)) continue; fn.call(context, arr[i], i, this) && filteredArr.push(arr[i]) } return filteredArr }
// ES5循环实现map
const selfMap = function (fn, context) { let arr = Array.prototype.slice.call(this) let mappedArr = [] for (let i = 0; i < arr.length; i++) { // 判断稀疏数组的情况 if (!arr.hasOwnProperty(i)) continue; mappedArr.push(fn.call(context, arr[i], i, this)) } return mappedArr }
// reduce实现map
const selfMap2 = function (fn, context) { let arr = Array.prototype.slice.call(this) return arr.reduce((pre, cur, index) => { return [...pre, fn.call(context, cur, index, this)] }, []) }