简体   繁体   English

有人能解释一下“forEach”方法在下面的代码中是如何工作的吗?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM