map:
Array.prototype.myMap = function (fn) {
const arr = this;
const result = [];
for (let i = 0; i < arr.length; i++) {
result.push(fn.call(arr, arr[i], i, arr))
}
return result
}
filter:
Array.prototype.myFilter = function (fn) {
const arr = this;
const result = [];
for (let i = 0; i < arr.length; i++) {
const boolean = fn.call(arr, arr[i], i, arr)
boolean && result.push(arr[i])
}
return result
}
reduce:
Array.prototype.myReduce = function (fn, value) {
const arr = this
if (arr.length === 0) return
let result = value || arr[0]
let startIndex = value ? 0 : 1
for (let i = startIndex; i < arr.length; i++) {
result = fn.call(arr, result, arr[i], i, arr)
}
return result
}
使用:
const arr = [1, 2, 3, 4, 5]
const arr1 = arr.myMap((item, idx, arr) => item + idx + arr[1])
const arr2 = arr.myFilter(item => item % 2 === 1)
const arr3 = arr.myReduce((acc, cur) => {
acc = acc + '' + cur
return acc
}, '')