手写map方法
map 方法返回的是一个新的数组。这个数组中的每一项,是数组map中的回调函数处理后的值。
Array.prototype.map2 = function(callBack){
let len = this.length
let newArr = []
if(typeof callBack !== 'function'){
throw new Error('must be function')
}
for(let i =0;i<len;i++){
newArr.push(callBack.call(this,this[i],i))
}
return newArr
}
let arr = [1,2,3]
let arr2 = arr.map2(item=>item*2)
console.log(arr2)
手写reduce方法
reduce方法常用来累加求和,或者拿来处理做一些对象的转化。
reduce是数组遍历方法中比较复杂的一个。它的回调函数接收四个参数pre,now,index,arr
pre是上一轮循环return返回的值 ,now是当前循环到的数组的元素。index是当前遍历的数组的下标。arr就是遍历的数组本身。
Array.prototype.reduce2 = function(callBack,init){
let i = 0
let len = this.length
let pre = init
if(init === undefined){
pre = this[0]
i = 1
}
for(i;i<len;i++){
pre = callBack.call(this,pre,this[i],i,this)
}
return pre
}
let arr = [1,2,3]
let sum = arr.reduce2((pre,cur)=>{
return pre + cur
},0)
console.log(sum)
手写filter函数
filter是过滤,返回的是一个新数组。
新数组的元素是经过fliter的回调处理的。filter的回调的返回值必须是一个布尔值。如果为真,则新数组会接收,如果为假,则直接过滤。
Array.prototype.filter2 = function(callBack){
let newArr = []
for(let i =0;i<this.length;i++){
if(callBack(this[i])){
newArr.push(this[i])
}
}
return newArr
}
let arr = [1,2,3,4,5,6]
let arr2 = arr.filter2(item=>item>3)
console.log(arr2)
函数式编程之编写自定义高阶函数
编写自定义高阶函数的时候,需要注意两点
1尽量使用纯函数,减少函数的副作用
2 回调函数调用的时候记得使用call或者apply来绑定this指向。call和apply的区别主要在于,如果你给回调函数的参数个数是确定的,就用call,反之则用apply
定义高阶函数:
实现对象的一个过滤功能,返回值是一个数组,如果对象中的值满足条件,则把对象的key放到数组中去。
function filter(data,fn){
let obj = Object.create(data)
let arr = []
for(let item in obj){
if(fn.call(this,obj[item])){
arr.push(item)
}
}
return arr
}
let obj = {
'zhangsan':90,
'lisi':80,
'wangwu':70,
'zhaosi':99
}
let arr = filter(obj,(value)=>{
return value >79
})
console.log(arr)