在 JavaScript 中,map() 方法是 Array 对象的一个原生方法,用来对数组中的每个元素执行一个指定的函数,并返回一个新的数组,新数组中的元素是原数组元素按指定函数处理后的结果。
语法
array.map(function(currentValue, index, arr), thisValue)
function(currentValue, index, arr): 必需。函数,数组中的每个元素都会执行该函数。currentValue: 必需。当前元素的值。index: 可选。当前元素的索引。arr: 可选。当前元素所属的数组对象。
thisValue: 可选。对象,执行回调函数时使用的 this 值。
示例
将数组中的每个元素加倍
const numbers = [1, 2, 3, 4, 5];
const doubledNumbers = numbers.map(function(num) {
return num * 2;
});
console.log(doubledNumbers); // [2, 4, 6, 8, 10]将数组中的字符串转为大写
const words = ['hello', 'world', 'javascript'];
const upperCaseWords = words.map(function(word) {
return word.toUpperCase();
});
console.log(upperCaseWords); // ['HELLO', 'WORLD', 'JAVASCRIPT']获取数组中每个元素的索引
const fruits = ['apple', 'banana', 'cherry'];
const fruitsWithIndex = fruits.map(function(fruit, index) {
return `${fruit} is at index ${index}`;
});
console.log(fruitsWithIndex); // ['apple is at index 0', 'banana is at index 1', 'cherry is at index 2']注意事项
map()方法不会改变原数组,而是返回一个新的数组。- 如果
thisValue参数被提供,它将被作为函数的 this 值。 map()方法不会对空数组进行检测,所以在使用时需要确保数组中有元素。
希望本文对你理解 JavaScript 中的 map() 方法有所帮助。祝学习愉快!