EASY
Given an integer array nums
, a reducer function fn
, and an initial value init
, return a reduced array.
A reduced array is created by applying the following operation: val = fn(init, nums[0])
, val = fn(val, nums[1])
, val = fn(val, nums[2])
, ...
until every element in the array has been processed. The final value of val
is returned.
If the length of the array is 0, it should return init
.
Please solve it without using the built-in Array.reduce
method.
接受參數 整數陣列nums
、歸約函數fn
、初始值init
,並返回一個歸約陣列。
通過操作創建歸約陣列:val = fn(init, nums[0])
, val = fn(val, nums[1])
, val = fn(val, nums[2])
, ...
直到陣列中的每個元素都被處理完畢。返回 val 的最終值。
如果陣列長度為 0,則返回 init。
請在沒有使用Array.reducer()的情況下解決這個問題。
const reduce = (nums, fn, init) => {
if (nums.length == 0) {return init;};
let val = init;
//...累加邏輯
return val;
}
val = fn(val, nums[i]);
init的0+1,val=1;
、1+4,val=5,
、5+5,val=10
...類推。const reduce = (nums, fn, init) => {
if (nums.length == 0) {return init;};
let val = init;
for (let i = 0; i < nums.length; i++) {
val = fn(val, nums[i]);
}
return val;
}
let nums1 = [1,2,3,4]
function sum1(accum, curr) { return accum + curr; }
let init1 = 0
console.log(reduce(nums1,sum1,init1));
let nums2 = [1,2,3,4]
function sum2(accum, curr) { return accum + curr * curr; }
let init2 = 100
console.log(reduce(nums2,sum2,init2));
let nums3 = []
function sum3(accum, curr) { return 0; }
let init3 = 25
console.log(reduce(nums3,sum3,init3));