在JavaScript中,高阶函数(Higher-Order Function)是一种特殊的函数
它至少满足以下两个条件之一
- 接受一个或多个函数作为参数
- 返回一个函数作为结果
高阶函数在JavaScript中非常常见,它们使得代码更加灵活和可重用
下面是一些常见的使用高阶函数
高阶函数重写(Array method)
1. forEach
Array.prototype.myForEach = function (callback) {
// 参数验证,确保 callback 是一个函数
if (typeof callback !== 'function') {
throw new TypeError(callback + ' is not a function');
}
for (let i = 0; i < this.length; i++) {
callback(this[i], i, this);
}
}
const arr = [1, 2, 3, 4, 5];
arr.myForEach((item, index, arr) => {
console.log(item);
});
// 打印结果
1
2
3
4
5
2. map
Array.prototype.myMap = function (callback) {
// 参数验证,确保 callback 是一个函数
if (typeof callback !== 'function') {
throw new TypeError(callback + ' is not a function');
}
const newArr = [];
for (let i = 0; i < this.length; i++) {
newArr.push(callback(this[i], i, this));
}
return newArr;
}
const arr = [1, 2, 3, 4, 5];
const newArr = arr.myMap((item, index, arr) => {
return item * 2;
});
console.log(newArr);
// 打印结果
[ 2, 4, 6, 8, 10 ]
3. filter
Array.prototype.myFilter = function (callback) {
// 参数验证,确保 callback 是一个函数
if (typeof callback !== 'function') {
throw new TypeError(callback + ' is not a function');
}
const newArr = [];
for (let i = 0; i < this.length; i++) {
if(callback(this[i], i, this)){
newArr.push(this[i]);
}
}
return newArr;
}
const arr = [1, 2, 3, 4, 5];
const newArr = arr.myFilter((item, index, arr) => {
return item > 2;
});
console.log(newArr);
// 打印结果
[ 3, 4, 5 ]
4. find
Array.prototype.myFind = function (callback) {
// 参数验证,确保 callback 是一个函数
if (typeof callback !== 'function') {
throw new TypeError(callback + ' is not a function');
}
for (let i = 0; i < this.length; i++) {
// 如果 callback 返回 true,则返回当前元素
if (callback(this[i], i, this)) {
return this[i];
}
}
return undefined;
}
const arr = [1, 2, 3, 4, 5];
const findVal = arr.myFind((item, index, arr) => {
return item*item === 4;
});
console.log(findVal);
// 打印结果
2
5. some
Array.prototype.mySome = function (callback) {
// 参数验证,确保 callback 是一个函数
if (typeof callback !== 'function') {
throw new TypeError(callback + ' is not a function');
}
for (let i = 0; i < this.length; i++) {
// 如果 callback 返回 true,则返回当前元素
if (callback(this[i], i, this)) {
return true;
}
}
return false;
}
const arr = [1, 2, 3, 4, 5];
const findVal = arr.mySome((item, index, arr) => {
return item*item === 8;
});
console.log(findVal);
//打印结果
false
- every
Array.prototype.myEvery = function (callback) {
// 参数验证,确保 callback 是一个函数
if (typeof callback !== 'function') {
throw new TypeError(callback + ' is not a function');
}
// let res = true;
for (let i = 0; i < this.length; i++) {
if (!callback(this[i], i, this)) {
return false;
}
}
return true;
}
const arr = [1, 2, 3, 4, 5];
const everyVal = arr.myEvery((item, index, arr) => {
return item > 0;
});
console.log(everyVal);
// 打印结果
true