JavaScript - map

作者: YongjieBook | 来源:发表于2024-01-23 14:09 被阅读0次

map 是 JavaScript 中数组的一个高阶函数,用于遍历数组的每个元素并对每个元素执行提供的回调函数。map 返回一个新的数组,其中包含回调函数的返回值。

基本语法

const newArray = array.map((currentValue, index, array) => {
  // 回调函数逻辑
  // 返回值将被添加到新数组中
  return transformedValue;
});
  • currentValue:当前遍历到的元素的值。
  • index:当前遍历到的元素的索引。
  • array:原始数组。

示例

1. 将数组中每个元素加倍

const numbers = [1, 2, 3, 4, 5];

const doubledNumbers = numbers.map(num => num * 2);

console.log(doubledNumbers); // [2, 4, 6, 8, 10]

2. 将字符串数组转换为大写

const words = ['apple', 'banana', 'cherry'];

const uppercasedWords = words.map(word => word.toUpperCase());

console.log(uppercasedWords); // ['APPLE', 'BANANA', 'CHERRY']

3. 获取数组中每个元素的长度

const fruits = ['apple', 'banana', 'cherry'];

const lengths = fruits.map(fruit => fruit.length);

console.log(lengths); // [5, 6, 6]

4. 使用索引创建新数组

const numbers = [1, 2, 3, 4, 5];

const indexedNumbers = numbers.map((num, index) => num * (index + 1));

console.log(indexedNumbers); // [1, 4, 9, 16, 25]

5. 对象数组转换

const users = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' },
  { id: 3, name: 'Charlie' },
];

const userIds = users.map(user => user.id);

console.log(userIds); // [1, 2, 3]

注意事项

  • map 不会修改原始数组,而是返回一个新的数组。
  • 回调函数中的逻辑应当是纯函数,不应该改变原始数组或其他外部状态。
  • 如果不需要返回新数组,而只是对数组进行遍历,可以使用 forEach
  • 使用 map 时,确保回调函数返回值的类型和期望的类型一致,以避免意外行为。

相关文章

网友评论

    本文标题:JavaScript - map

    本文链接:https://www.haomeiwen.com/subject/gkouodtx.html