題目:
Given an integer array and a mapping function, return a new arry with a transformation applied to each element. arr fn
The return array should be created such that .retrunedArray[i] = fn(arr[i], i)
Please solve it without the built-in method. Array.map
題目理解是:回傳一個新陣列,而新陣列的組成是由透過function傳入的舊陣列執行而得出得。
範例一:
Input: arr = [1, 2, 3], fn = function plusone(n) { return n + 1; }
Output: [2, 3, 4]
新陣列就是舊陣列 + 1
範例二:
Input: arr = [1, 2, 3], fn = function plusI(n, i) { return n + i; }
Output: [1, 3, 5]
首先當位址(i = 0)時,新陣列[i=0]時就是舊陣列[i=0]=1 + i = 1 + 0;
再來是位址(i = 1)時,新陣列[i=1]時就是舊陣列[i=1]=2 + 1 = 2 + 1;
最後是位址(i = 2)時,新陣列[i=2]時就是舊陣列[i=2]=3 + 2 = 3 + 2;
範例三:
Input: arr = [10, 20, 30], fn = function constant() { return 42; }
Output: [42, 42, 42]
新陣列就是都是回傳42
解題:
var map = function(arr, fn) {
let ary = [];
for (let i = 0; i < arr.length; i++)
{
ary.push(fn(arr[i], i));
}
return ary;
};
思路是針對傳入的arr長度製作一個新的陣列ary,
並且使用push,將運算所得的值放進新陣列。