React Native

JavaScript - map

2024-01-23  本文已影响0人  YongjieBook

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

基本语法

const newArray = array.map((currentValue, index, array) => {
  // 回调函数逻辑
  // 返回值将被添加到新数组中
  return transformedValue;
});

示例

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]

注意事项

上一篇 下一篇

猜你喜欢

热点阅读