EASY
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).
接受一個整數陣列arr
和映射函數fn
並且返回對原陣列進行應用轉換後的新陣列。
返回的陣列應創建為 returnedArray[i] = fn(arr[i], i)
。
Please solve it without the built-in Array.map method.
請在沒有使用Array.map()的情況下解決這個問題。
const map = (arr,fn)=>{
let returnedArray = [];
...
return returnedArray;
}
returnedArray[i] = fn(arr[i], i)
returnedArray
const map = (arr,fn)=>{
let returnedArray = [];
for(let i=0;i<arr.length;i++){
returnedArray.push(fn(arr[i],i));
};
return returnedArray;
}
let arr1 = [1,2,3];
let fn1 = function plusone(n) { return n + 1; };
console.log(map(arr1,fn1));
let arr2 = [1,2,3];
let fn2 = fn = function plusI(n, i) { return n + i; }
console.log(map(arr2,fn2));
let arr3 = [10,20,30];
let fn3 = fn = function constant() { return 42; }
console.log(map(arr3,fn3));