什么是高阶函数?
一个函数中有参数是函数,或者返回值是函数,这样的函数就是高阶函数。
下面这个例子中的fn就是高阶函数
const callback = ()=>{
console.log('我是fn的参数');
}
const fn = (callback)=>{
callback();
}
fn(callback);
我们平常使用的高阶函数有哪些呢?
其实有很多高阶函数,比如数组中的方法forEach,map,every,some等等都是高阶函数,还有react-redux中的connect函数也是高阶函数,其使用形式:connect()(Component)。
我们自己来写一下这几个数组方法的实现。
因为每一个数组都可以调用这些方法,所以这些方法写在原型上是最好的。
forEach的实现
Array.prototype.myForEach = function (callback) {
if (!Array.isArray(this)) {
throw new Error(`${array} is not a Array`);
}
if (typeof callback!== 'function') {
throw new Error(`${callback} is not a Function`);
}
let that = this;
for (let i = 0; i < that.length; i++) {
callback(that[i]);//return 或者 break或者continue 没有用是应为每次的循环都是在一个函数内部进行的
}
}
const arr = [1, 2];
arr.myForEach((item)=>{
console.log(item);
});
![]()
map的实现
Array.prototype.myMap = function(fn){
if(!Array.isArray(this)){
throw new Error(`${this} is not a Array`);
}
if(typeof fn !== 'function'){
throw new Error(`${fn} is not a Function`);
}
let newArr = [];
for(const value of this){
newArr.push(fn(value));
}
return newArr;
}
const result = [1,2,3];
console.log(result.myMap(item=>item*item));
![]()
every的实现
Array.prototype.myEvery = function(callback){
if(!Array.isArray(this)){
throw new Error(`${this} is not a Array`);
}
if(typeof callback!== 'function'){
throw new Error(`${callback} is not a Function`);
}
let flag = true;
for(const value of this){
flag = callback(value);
if(!flag){
break;
}
}
return flag;
}
const arr = [1,2,3];
const result1 = arr.myEvery((item)=>item>0);
const result2 = arr.myEvery((item)=>item>1);
console.log(result1);
console.log(result2);
some的实现
Array.prototype.some = function(fn){
if(!Array.isArray(this)){
throw new Error(`${this} is not a Array`);
}
if(typeof fn !== 'function'){
throw new Error(`${fn} is not a Function`);
}
let flag = false;
for(const value of this){
flag = fn(value);
if(flag){
break;
}
}
return flag;
}
const arr = [1,2,3];
console.log(arr.some((item)=>item>-1));
console.log(arr.some((item)=>item>4));
![]()
数组中有很多方法的原理都是如此,把每一个元素通过用传入的回调函数进行处理,这样可以让函数变得更加灵活。
博客介绍了JavaScript高阶函数,即参数或返回值为函数的函数,如数组的forEach、map、every、some方法及react - redux的connect函数。还阐述了可将这些数组方法写在原型上,并打算自行实现这些方法,通过回调函数处理元素让函数更灵活。
259

被折叠的 条评论
为什么被折叠?



