const list = [1, 2, 3]
Array.prototype.myForeach = function (fn) {
for (let i = 0; i < this.length; i++) {
fn(this[i], i, this)
}
}
Array.prototype.myMap = function (fn) {
const _list = []
for (let i = 0; i < this.length; i++) {
_list.push(fn(this[i], i, this))
}
return _list
}
Array.prototype.myFilter = function (fn) {
const _list = []
for (let i = 0; i < this.length; i++) {
!!fn(this[i], i, this) && _list.push(this[i])
}
return _list
}
Array.prototype.mySome = function (fn) {
const _list = []
for (let i = 0; i < this.length; i++) {
if (!!fn(this[i], i, this)) {
return true
}
}
return false
}
Array.prototype.myFind = function (fn) {
const _list = []
for (let i = 0; i < this.length; i++) {
if (!!fn(this[i], i, this)) {
return this[i]
}
}
}
Array.prototype.myFindIndex = function (fn) {
const _list = []
for (let i = 0; i < this.length; i++) {
if (!!fn(this[i], i, this)) {
return i
}
return -1
}
}
Array.prototype.myReverse = function (fn) {
const _list = []
for (let i = this.length - 1; i >= 0; i--) {
_list.push(this[i])
}
return _list
}
Array.prototype.myReduce = function (fn, num) {
let _num = num
for (let i = 0; i < this.length; i++) {
_num = fn(_num, this[i], i, this)
}
return _num
}
标签:function,return,JavaScript,list,let,数组,prototype,重写,fn
From: https://www.cnblogs.com/landuo629/p/17919698.html