JS array method map, filter, reduce method implementation
1.map
Array.prototype._map = function(fn) {
if (this.length < 1) return
let newArr = []
for (let i = 0; i < this.length; i++) {
newArr.push(fn(this[i], i, this))}return newArr
}
Copy the code
2.filter
Array.prototype._filter = function(fn) {
if (this.length < 1) return
let newArr = []
for (let i = 0; i < this.length; i++) {
if (fn(this[i], i, this)) {
newArr.push(this[i])
}
}
return newArr
}
Copy the code
3.reduce
Array.prototype._reduce = function (fn, initValue) {
if (initValue === undefined&&!this.length) {
throw new Error("myReduce of empty array with no initial value")}let result = initValue ? initValue : this[0]
for (let i = initValue ? 0 : 1; i < this.length; i++) {
result = fn(result, this[i], i, this)}return result
}
Copy the code