filter
Array
.prototype
.myFilter = function (callback
, thisArg
) {
const res
= []
const obj
= new Object(this)
const len
= obj
.length
>>> 0
for (let i
= 0; i
< len
; i
++) {
if (i
in obj
) {
if (callback
.call(thisArg
, obj
[i
], i
, this)) {
res
.push(obj
[i
])
}
}
}
return res
}
map
Array
.prototype
.myMap = function (callback
, thisArg
) {
const res
= []
const obj
= new Object(this)
const len
= obj
.length
>>> 0
for (let i
= 0; i
< len
; i
++) {
if (i
in obj
) {
res
[i
] = callback
.call(thisArg
, obj
[i
], i
, this)
}
}
return res
}
forEach
Array
.prototype
.myForEach = function (callback
, thisArg
) {
const obj
= new Object(this)
const len
= obj
.length
>>> 0
for (let i
= 0; i
< len
; i
++) {
if (i
in obj
) {
callback
.call(thisArg
, obj
[i
], i
, this)
}
}
}
reduce
Array
.prototype
.myReduce = function (callback
, initialValue
) {
const obj
= new Object(this)
const len
= obj
.length
>>> 0
let accumulator
= initialValue
let i
= 0
if (accumulator
== undefined
) {
while (i
< len
&& !(i
in obj
)) {
i
++
}
accumulator
= obj
[i
++]
}
while (i
< len
) {
if (i
in obj
) {
accumulator
= callback
.call(undefined
, accumulator
, obj
[i
], i
, this)
}
i
++
}
return accumulator
}
转载请注明原文地址:https://blackberry.8miu.com/read-35764.html