简体   繁体   中英

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.

I don't understand how the callback (acc, el, index, arr) portion brings in the "add" function. With 2 parameters of (a, b) where does the parameters of the forEach come into play?

 // 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 .

Then when you call array.forEach() , your function does acc = callback(acc, el, index, arr) , which calls 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). The result is stored back in acc , which will be passed again on the next iteration of forEach() .

BTW, the code that initializes acc doesn't look right. You shouldn't be testing whether arr is an array (it has to be), you should check whether initial was supplied.

var acc;
if (initial === undefined) {
    acc = arr[0];
    arr = arr.slice(1);
} else {
    acc = initial;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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