[英]Can someone explain how the “forEach” method works in the code below?
For the problem, I was tasked to create a function that mimics the reduce method and test it against the following where I should get the answer of 8.对于这个问题,我的任务是创建一个模仿 reduce 方法的 function 并针对以下内容进行测试,我应该得到 8 的答案。
I don't understand how the callback (acc, el, index, arr) portion brings in the "add" function.我不明白回调(acc、el、index、arr)部分如何引入“add”function。 With 2 parameters of (a, b) where does the parameters of the forEach come into play?
对于 (a, b) 的 2 个参数,forEach 的参数在哪里发挥作用?
// function to mimic reduce
function reduce(array, callback, initial) {
if(Array.isArray(array) {
let acc;
if (initial === undefined) {
acc = array[0];
array = array.slice(1);
} else {
acc = initial;
}
array.forEach(function(el, index, arr) {
acc = callback(acc, el, index, arr);
});
return acc;
}
return "The first arg should be an array";
}
// Code to test against reduce function
var nums = [4, 1, 3]
var add = function(a, b) { return a + b;}
reduce(nums, add, 0) // answer is 8
When you call你打电话时
reduce(nums, add, 0);
nums
becomes the value of array
, add
becomes the value of callback
, and 0
becomes the value of initial
. nums
成为array
的值, add
成为callback
的值, 0
成为initial
的值。
Then when you call array.forEach()
, your function does acc = callback(acc, el, index, arr)
, which calls add()
.然后,当您调用
array.forEach()
时,您的 function 执行acc = callback(acc, el, index, arr)
,它调用add()
。 Inside add()
, a
gets the value of acc
and b
gets the value of el
(the other two arguments you pass to callback
are being ignored by add
-- most reduction functions don't need to use them, but they're passed for completeness).在
add()
中, a
获取acc
的值, b
获取el
的值(传递给callback
的另外两个 arguments 被add
忽略 - 大多数归约函数不需要使用它们,但它们已通过为了完整性)。 The result is stored back in acc
, which will be passed again on the next iteration of forEach()
.结果存储回
acc
中,将在forEach()
的下一次迭代中再次传递。
BTW, the code that initializes acc
doesn't look right.顺便说一句,初始化
acc
的代码看起来不正确。 You shouldn't be testing whether arr
is an array (it has to be), you should check whether initial
was supplied.您不应该测试
arr
是否是一个数组(它必须是),您应该检查是否提供了initial
。
var acc;
if (initial === undefined) {
acc = arr[0];
arr = arr.slice(1);
} else {
acc = initial;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.