js map实现
map 方法的基本用法
map 是 JavaScript 数组的一个高阶函数,用于对数组中的每个元素执行指定操作并返回一个新数组。原数组不会被修改。
const numbers = [1, 2, 3];
const doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6]
参数说明
map 方法接受两个参数:
- 回调函数:对每个元素执行的操作,可接收三个参数(当前元素、当前索引、原数组)。
- thisArg(可选):指定回调函数中
this的值。
const users = [{ name: 'Alice' }, { name: 'Bob' }];
const names = users.map(function(user) {
return user.name + this.suffix;
}, { suffix: '!' });
console.log(names); // ['Alice!', 'Bob!']
实现原理
map 方法的底层实现可以模拟如下:

Array.prototype.myMap = function(callback, thisArg) {
const result = [];
for (let i = 0; i < this.length; i++) {
result.push(callback.call(thisArg, this[i], i, this));
}
return result;
};
使用场景
-
数据转换:将对象数组提取特定属性。
const products = [{ id: 1, price: 10 }, { id: 2, price: 20 }]; const prices = products.map(product => product.price); -
链式调用:与其他数组方法结合使用。

const numbers = [1, 2, 3, 4]; const squaredEven = numbers .filter(n => n % 2 === 0) .map(n => n * n);
注意事项
-
稀疏数组:空元素会被跳过,但保留在结果数组中。
const arr = [1, , 3]; const result = arr.map(x => x * 2); // [2, empty, 6] -
性能考虑:大数据量时可能影响性能,可考虑
for循环优化。 -
异步处理:直接使用
map无法处理异步操作,需结合Promise.all。const urls = ['url1', 'url2']; const fetchData = urls.map(async url => await fetch(url));






