`map()` 是 JavaScript 數組提供的一個高階函數,它用于對數組中的每個元素執行指定的函數,并返回一個新的數組,新數組中的元素是原數組中的每個元素經過函數處理后的結果。
`map()` 函數的語法如下:
```javascript
array.map(callback(currentValue, index, array), thisArg);
```
其中:
- `callback` 是一個函數,它會被應用到數組中的每個元素上,并且會接收三個參數:
? - `currentValue`:當前正在被處理的元素。
? - `index`(可選):當前元素的索引。
? - `array`(可選):調用 `map()` 方法的數組。
- `thisArg`(可選):傳遞給 `callback` 函數的 `this` 值。
`map()` 函數會返回一個新數組,其中每個元素都是由 `callback` 函數返回的結果。原始數組不會受到影響。
下面是一些關于 `map()` 函數的例子:
1. **對數組中的每個元素進行平方操作:**
```javascript
const numbers = [1, 2, 3, 4, 5];
const squaredNumbers = numbers.map(num => num * num);
console.log(squaredNumbers); // [1, 4, 9, 16, 25]
```
2. **將數組中的字符串元素轉換為大寫:**
```javascript
const fruits = ["apple", "banana", "orange"];
const capitalizedFruits = fruits.map(fruit => fruit.toUpperCase());
console.log(capitalizedFruits); // ["APPLE", "BANANA", "ORANGE"]
```
3. **將對象數組中的特定屬性提取出來:**
```javascript
const people = [
? { name: "Alice", age: 30 },
? { name: "Bob", age: 25 },
? { name: "Charlie", age: 40 }
];
const names = people.map(person => person.name);
console.log(names); // ["Alice", "Bob", "Charlie"]
```
4. **計算數組中每個數字的平均值:**
```javascript
const scores = [85, 90, 78, 95, 88];
const average = scores.reduce((total, score) => total + score, 0) / scores.length;
console.log(average); // 87.2
```
`map()` 函數非常有用,它可以讓你在不修改原始數組的情況下對數組的每個元素進行操作,并生成一個新的數組。它在函數式編程中廣泛用于數據轉換和操作。