JavaScript手写数组常用方法实现详解

作者:纸飞机

时间:2026-10-23

浏览:316

本文详细解析JavaScript中数组常用原型方法的手写实现,涵盖forEach、filter、find、map、some、every、reduce等核心API。通过扩展Array.prototype,深入讲解回调函数执行机制、this指向处理及边界条件,帮助开发者理解底层逻辑并提升代码掌控力。

文章目录

前言

在前端开发实践中,数组操作极为频繁,开发者经常调用 forEach、filter、find、findIndex、map、some、every、reduce 以及 reduceRight 等内置方法。

本文将尝试手动实现上述数组方法,为便于演示,代码将直接扩展至 Array 的 prototype 对象上。

完整代码已上传至 GitHub,往期文章亦已分类整理,欢迎查阅。

正文

参数说明

callbackFn:回调函数。

thisArg:执行 callbackFn 时绑定的 this 值。

currentValue:当前正在处理的数组元素。

index:当前元素的索引值。

array:调用该方法的源数组。

accumulator:累加器,用于累积回调函数的返回值。

initialValue:作为第一次调用 callbackFn 时 accumulator 参数的初始值,仅 reduce 和 reduceRight 使用。

element:当前处理的数组元素,即自定义实现中的 this 指向对象。

forEach 函数

语法:arr.forEach(callbackFn(currentValue [, index [, array]])[, thisArg])

功能:对数组中的每个元素执行一次提供的回调函数。

返回值:undefined。

自定义实现:myForEach。


Array.prototype.myForEach = function(callbackFn, thisArg) {
 if (typeof callbackFn !== 'function') throw ('callbackFn参数必须是函数');
 let element = this,
 len = element && element.length || 0;
 if (!thisArg) thisArg = element;
 for (let index = 0; index < len; index++) {
 callbackFn.call(thisArg, element[index], index, element);
 }
};

filter 函数

语法:var newArray = arr.filter(callbackFn(currentValue[, index[, array]])[, thisArg])

功能:创建一个新数组,包含所有通过测试函数的元素。

返回值:由通过测试的元素组成的新数组;若无元素通过测试,则返回空数组。

自定义实现:myFilter。


Array.prototype.myFilter = function(callbackFn, thisArg) {
 if (typeof callbackFn !== 'function') throw ('callbackFn参数必须是函数');
 let element = this,
 len = element && element.length || 0,
 result = [];
 if (!thisArg) thisArg = element;
 for (let index = 0; index < len; index++) {
 if (callbackFn.call(thisArg, element[index], index, element)) result.push(element[index]);
 }
 return result;
};

find 函数

语法:arr.find(callbackFn[, thisArg])

功能:返回数组中第一个满足测试函数的元素值,若未找到则返回 undefined。

返回值:满足测试条件的第一个元素值,否则为 undefined。

自定义实现:myFind。


Array.prototype.myFind = function(callbackFn, thisArg) {
 if (typeof callbackFn !== 'function') throw ('callbackFn参数必须是函数');
 let element = this,
 len = element && element.length || 0;
 if (!thisArg) thisArg = element;
 for (let index = 0; index < len; index++) {
 if (callbackFn.call(thisArg, element[index], index, element)) {
  return element[index];
 }
 }
 return
}

findIndex 函数

语法:arr.findIndex(callbackFn[, thisArg])

功能:返回数组中第一个满足测试函数的元素索引。

返回值:满足测试条件的第一个元素的索引;若未找到,返回 -1。

自定义实现:myFindIndex。


Array.prototype.myFindIndex = function(callbackFn, thisArg) {
 if (typeof callbackFn !== 'function') throw ('callbackFn参数必须是函数');
 let element = this,
 len = element && element.length || 0;
 if (!thisArg) thisArg = element;
 for (let index = 0; index < len; index++) {
 if (callbackFn.call(thisArg, element[index], index, element)) return index;
 }
 return -1;
}

fill 函数

语法:arr.fill(value[, start[, end]])

功能:用一个固定值填充数组,范围从起始索引到终止索引(不含终止索引)。

返回值:修改后的原数组。

自定义实现:myFill。


Array.prototype.myFill = function(value, start = 0, end) {
 let element = this,
 len = element && element.length || 0;
 end = end || len;
 let loopStart = start < 0 ? 0 : start, // 设置循环开始值
 loopEnd = end >= len ? len : end; // 设置循环结束值

 for (; loopStart < loopEnd; loopStart++) {
 element[loopStart] = value;
 }
 return element;
}

map 函数

语法:var new_array = arr.map(function callbackFn(currentValue[, index[, array]]) {// Return element for new_array }[, thisArg])

功能:创建一个新数组,其元素是原数组每个元素调用一次回调函数后的返回值。

返回:测试数组中是不是至少有1个元素通过了被提供的函数测试。它返回的是一个Boolean类型的值。 一个由原数组每个元素执行回调函数的结果组成的新数组。

自定义实现:myMap。


Array.prototype.myMap = function(callbackFn, thisArg) {
 if (typeof callbackFn !== 'function') throw ('callbackFn参数必须是函数');
 let element = this,
 len = element && element.length || 0,
 result = [];
 if (!thisArg) thisArg = element;
 for (let index = 0; index < len; index++) {
 result[index] = callbackFn.call(thisArg, element[index], index, element);
 }
 return result;
}

some 函数

语法:arr.some(callbackFn(currentValue[, index[, array]])[, thisArg])

功能:测试数组中是否至少有一个元素通过提供的测试函数,返回布尔值。

返回值:若至少有一个元素通过测试返回 true,否则返回 false。

自定义实现:mySome。


Array.prototype.mySome = function(callbackFn, thisArg) {
 if (typeof callbackFn !== 'function') throw ('callbackFn参数必须是函数');
 let element = this,
 len = element && element.length || 0;
 if (!thisArg) thisArg = element;
 for (let index = 0; index < len; index++) {
 if (callbackFn.call(thisArg, element[index], index, element)) return true;
 }
 return false;
}

every 函数

语法:arr.every(callbackFn(currentValue[, index[, array]])[, thisArg])

功能:测试数组内所有元素是否都能通过指定函数的测试,返回布尔值。

返回值:若回调函数每次返回 true 则结果为 true,否则为 false。

自定义实现:myEvery。


Array.prototype.myEvery = function(callbackFn, thisArg) {
 if (typeof callbackFn !== 'function') throw ('callbackFn参数必须是函数');
 let element = this,
  len = element && element.length || 0;
 if (!thisArg) thisArg = element;
 for(let index = 0; index < len; index++) {
  if (!callbackFn.call(thisArg, element[index], index, element)) return false;
 }
 return true;
}

reduce 函数

语法:arr.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])

功能:对数组每个元素执行提供的 reducer 函数(升序执行),将结果汇总为单个值。

返回值:函数累计处理后的最终结果。

自定义实现:myReduce。


Array.prototype.myReduce = function(callbackFn, initialValue) {
 if (typeof callbackFn !== 'function') throw ('callbackFn参数必须是函数');
 let element = this,
  len = element.length || 0,
  index = 0,
  result;
 if (arguments.length >= 2) {
  result = arguments[1];
 } else {
  while (index < len && !(index in element)) index++;
  if (index >= len) throw new TypeError('Reduce of empty array ' + 'with no initial value');
  result = element[index++];
 }

 while (index < len) {
  if (index in element) result = callbackFn(result, element[index], index, element);
  index++;
 }
 return result;
}

reduceRight 函数

语法:arr.reduceRight(callback(accumulator, currentValue[, index[, array]])[, initialValue])

功能:接受一个累加器函数,从右向左遍历数组,将其减少为单个值。

返回值:执行后的最终返回值。

自定义实现:myReduceRight。


Array.prototype.myReduceRight = function(callbackFn, initialValue) {
 if (typeof callbackFn !== 'function') throw ('callbackFn参数必须是函数');
 let element = this,
  len = element.length || 0,
  index = len - 1,
  result;
 if (arguments.length >= 2) {
  result = arguments[1];
 } else {
  while (index >= 0 && !(index in element)) {
   index--;
  }
  if (index < 0) {
   throw new TypeError('reduceRight of empty array with no initial value');
  }
  result = element[index--];
 }
 for (; index >= 0; index--) {
  if (index in element) {
   result = callbackFn(result, element[index], index, element);
  }
 }
 return result;
}

最后

至此,关于 JavaScript 手写数组常用函数的总结介绍完毕。如需了解更多 JS 手写数组相关内容,请搜索本站往期文章或继续浏览其他文章,感谢大家的支持!

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章