P粉9094764572023-08-19 12:39:09
You have two problems, the first problem is that your updateDirectHelper
function does not return anything. Although there is a return
statement in this function, it is actually a callback function nested in reduce
(updateClause, [key, value]) => {
instead of updateDictHelper
itself.
Another question you have is how to provide a default value for acc
. Reduce natively supports the optional second parameter , which will be used as the initial value of acc
.
reduce(callbackFn, initialValue)
The best approach is to provide an initial value whenever possible. If you don't include it, .reduce()
will skip the first invocation of the callback and start calling the callback function with acc
set to the first value in the array, and set the second parameter to the second value in the array. If your array has only one value, as in your case, then this single value is the value returned from the .reduce()
call, and your .reduce()
The callback function will never be called:
const arrayWithOneElement = [1]; const res = arrayWithOneElement.reduce(() => { console.log("I never run"); }); // 注意没有第二个参数 console.log(res);