js实现map接收参数
map 方法的基本语法
在 JavaScript 中,Array.prototype.map 是一个高阶函数,用于遍历数组并对每个元素执行回调函数,最终返回一个新数组。其基本语法如下:

const newArray = array.map(callback(currentValue[, index[, array]])[, thisArg])
参数说明
-
callback- 必需参数,是一个函数,用于处理数组的每个元素。
- 接收三个参数:
currentValue:当前正在处理的元素。index(可选):当前元素的索引。array(可选):调用map的原始数组。
-
thisArg(可选)- 用于指定
callback函数中this的值。
- 用于指定
示例代码
基本用法
const numbers = [1, 2, 3];
const doubled = numbers.map((num) => num * 2);
console.log(doubled); // [2, 4, 6]
使用索引参数
const numbers = [1, 2, 3];
const withIndex = numbers.map((num, index) => `${index}: ${num}`);
console.log(withIndex); // ["0: 1", "1: 2", "2: 3"]
使用 thisArg
const obj = { multiplier: 10 };
const numbers = [1, 2, 3];
const multiplied = numbers.map(function(num) {
return num * this.multiplier;
}, obj);
console.log(multiplied); // [10, 20, 30]
注意事项
map不会修改原数组,而是返回一个新数组。- 如果未提供
thisArg,callback中的this默认为undefined(严格模式下)。 map会跳过空位(稀疏数组),但不会跳过undefined或null值。







