js map方法
在JavaScript中,map()
方法是一种用于数组的高阶函数。它接收一个回调函数作为参数,在数组的每个元素上调用该回调函数,并返回一个新的数组,其中包含的是回调函数的返回值。
语法
map()
方法的语法如下所示:
array.map(function(currentValue, index, arr), thisValue)
function(currentValue, index, arr)
: 回调函数,接收三个参数:currentValue
: 当前元素的值index
: 当前元素的索引arr
: 被操作的数组
thisValue
(可选): 在执行回调函数时使用的值,用作this
示例
让我们通过一个简单的示例来演示map()
方法的使用。假设我们有一个数组,想要把数组中的每个元素都乘以2,并返回一个新的数组。
const numbers = [1, 2, 3, 4, 5];
const doubledNumbers = numbers.map(function(num) {
return num * 2;
});
console.log(doubledNumbers);
在上面的代码中,我们使用map()
方法对numbers
数组中的每个元素都乘以2,并把结果存储在doubledNumbers
数组中。接下来,我们来看一下运行结果:
[2, 4, 6, 8, 10]
使用箭头函数
除了传统的匿名函数外,我们还可以使用箭头函数来简化代码。让我们使用箭头函数重写上面的示例:
const numbers = [1, 2, 3, 4, 5];
const doubledNumbers = numbers.map(num => num * 2);
console.log(doubledNumbers);
这样就可以更加简洁地实现相同的功能。
使用index参数
有时候我们可能还需要使用到元素的索引。让我们通过一个示例来说明:
const names = ['Alice', 'Bob', 'Charlie'];
const indexedNames = names.map(function(name, index) {
return `{name}({index + 1})`;
});
console.log(indexedNames);
上面的代码中,我们把每个名字与其索引拼接起来,并存储在indexedNames
数组中。接下来,我们来看一下运行结果:
["Alice(1)", "Bob(2)", "Charlie(3)"]
使用arr参数
除了元素的值和索引外,我们还可以使用数组本身。让我们通过一个示例来说明:
const numbers = [1, 2, 3, 4, 5];
const sumSoFar = [];
const runningSum = numbers.map(function(num, index, arr) {
if (index === 0) {
sumSoFar.push(num);
} else {
sumSoFar.push(num + sumSoFar[index - 1]);
}
return sumSoFar;
});
console.log(runningSum);
在上面的代码中,我们对numbers
数组求取了累加和,并把每一步的结果都存储在runningSum
数组中。接下来,我们来看一下运行结果:
[[1], [1, 3], [1, 3, 6], [1, 3, 6, 10], [1, 3, 6, 10, 15]]
使用thisValue参数
map()
方法还接受一个可选参数thisValue
,用来指定回调函数中的this。让我们通过一个示例来说明:
const numbers = [1, 2, 3, 4, 5];
const multiplier = 2;
const doubledNumbers = numbers.map(function(num) {
return num * this.multiplier;
}, { multiplier });
console.log(doubledNumbers);
在上面的代码中,我们通过指定this
来访问外部的变量multiplier
,并把数组中的每个元素都乘以2。接下来,我们来看一下运行结果:
[2, 4, 6, 8, 10]
总结
map()
方法是一个非常有用的数组方法,可以简化对数组的操作,并且可以返回一个新的数组,而不改变原数组。通过灵活运用回调函数,我们可以实现各种不同的需求。