(一下均为简单实现,没有考虑过多的edge case)
对于方法的基本使用不熟悉的话,可以上MDN查阅
对于map方法是十分重要的,React中没有像Vue中v-for指令一样的指令,只能传递数组,所以我们需要用到map方法对数组中的数据进行一些包装
map实现
Array.prototype.map = function (fn, thisValue = undefined) {
const res = [] //初始化返回结果
const target = fn.bind(thisValue) //为目标函数绑定this返回target函数
for (let i = 0; i < this.length; i++) {
//将target函数的返回值塞到res中
res.push(target(this[i], i, this))
}
return res
}
reduce实现
Array.prototype.treduce = function (fn, initialValue) {
//对返回值初始化,传了就用传递的参数,没传就是使用的数组第一项
let res = initialValue === undefined ? this[0]: initialValue
//遍历的时候也要判断是否传递参数
for (let i = initialValue === undefined ? 1 : 0; i < this.length; i++) {
res = fn(res, this[i], i, this)
}
return res
}
filter实现
Array.prototype.filter = function (fn, thisObject) {
//初始化返回结果
const res = []
// 为目标函数绑定this
const target = fn.bind(thisObject)
// 遍历执行目标函数,往res中塞执行结果为true的元素
for (let i = 0; i < this.length; i++) {
if (target(this[i], i, this)) {
res.push(this[i])
}
}
return res
}