---
# System prepended metadata

title: 2635.Apply Transform Over Each Element in Array
tags: [Array, leetCode]

---

# 2635.Apply Transform Over Each Element in Array

###### tags:`Array` | `leetCode`
<font color="#01AE9A" background="E1F3F0">`easy`</font>
 
### 題目
Given an integer array `arr` and a mapping function `fn`, return a new array with a transformation applied to each element.

The returned array should be created such that `returnedArray[i] = fn(arr[i], i)`.

Please solve it without the built-in `Array.map` method.
### Example
```javascript=
Input: arr = [1,2,3], fn = function plusone(n) { return n + 1; }
Output: [2,3,4]
Explanation:
const newArray = map(arr, plusone); // [2,3,4]
The function increases each value in the array by one. 
```
```javascript=
Input: arr = [1,2,3], fn = function plusI(n, i) { return n + i; }
Output: [1,3,5]
Explanation: The function increases each value by the index it resides in.
```
```javascript=
Input: arr = [10,20,30], fn = function constant() { return 42; }
Output: [42,42,42]
Explanation: The function always returns 42.
```

### Constraints
- `0 <= args.length <= 10`

---
### 解題邏輯
這題函式接受一個數字 `arr`和一個 `callback function`當作參數

```javascript=
var map = function(arr, fn) {
  let returnedArray = []
  for(let i =0;i<arr.length;i++){
   returnedArray.push(fn(arr[i],i))
  }
    return returnedArray
};
```
![](https://hackmd.io/_uploads/rJ0bQKUEh.png)


也可以寫成這樣
```javascript=
var map = function(arr, fn) {
  let returnedArray = []
  for(let i =0;i<arr.length;i++){
   returnedArray[i]=fn(arr[i],i)
  }
    return returnedArray
};
```
![](https://hackmd.io/_uploads/B1RxVFLE3.png)

### 觀念點
> A callback is defined as a function passed as an argument to another function.
> 這個函式只會在滿足了某個條件才會被動地去執行，我們就可以說這是一個 Callback function




<!-- {%hackmd @themes/orangeheart  %} -->
{%hackmd @themes/dracula %}