js map方法 实现

map方法的基本用法
JavaScript的map方法是数组原型上的一个高阶函数,用于对数组中的每个元素执行指定操作并返回新数组。语法如下:
const newArray = arr.map(callback(currentValue[, index[, array]])[, thisArg])
callback:对每个元素执行的函数,接受三个参数:currentValue:当前处理的元素index(可选):当前元素的索引array(可选):原数组
thisArg(可选):执行callback时用作this的值
实现自定义map方法
以下是手动实现map方法的Polyfill代码:
Array.prototype.myMap = function(callback, thisArg) {
if (this == null) {
throw new TypeError('Array.prototype.myMap called on null or undefined');
}
if (typeof callback !== 'function') {
throw new TypeError(callback + ' is not a function');
}
const originalArray = Object(this);
const len = originalArray.length >>> 0;
const newArray = new Array(len);
for (let i = 0; i < len; i++) {
if (i in originalArray) {
newArray[i] = callback.call(thisArg, originalArray[i], i, originalArray);
}
}
return newArray;
};
使用示例
const numbers = [1, 2, 3, 4];
// 原生map方法
const squared = numbers.map(x => x * x);
console.log(squared); // [1, 4, 9, 16]
// 自定义myMap方法
const cubed = numbers.myMap(x => x * x * x);
console.log(cubed); // [1, 8, 27, 64]
实现要点说明
- 类型检查:确保调用对象不为null/undefined,且callback是函数
- 长度处理:使用无符号右移操作符
>>> 0确保长度为非负整数 - 稀疏数组处理:通过
in操作符检查索引是否存在 - 上下文绑定:使用
call方法确保正确的this绑定
性能考虑
原生map方法通常经过浏览器优化,性能优于手动实现。自定义实现主要用于理解原理或在不支持ES5的环境中使用。实际项目中建议优先使用原生方法。







