Reduce() in depth

后端 未结 3 660
再見小時候
再見小時候 2021-01-22 01:31

In ES5, the new array method reduce(). I am wondering if someone can explain more in depth.

3条回答
  •  天涯浪人
    2021-01-22 01:56

    The method you pass into .reduce takes parameters previous_returned_value, current_iteration_item, current_iteration_index, context_array

    This means that each time it is called, the first argument is the return value from the previous invocation

    The initial value is what is passed in only the very first time.

    You can read the MDN docs about it here


    return an object form which key is idx and value is Math.pow(idx,2)

    • You pass in an initial empty object
    • Your method adds properties to this object
    • Method returns the object

    e.g.

     [1, 2, 3, 4, 5].reduce((o, e) => (o[e] = Math.pow(e, 2), o), {});
     // Object {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
    

    count how many letters are are in an array and turn it into the object

    • Again pass in an initial empty object
    • Method sets/adds 1 to the object based on the current letter
    • Method returns the object

    So again

    ['f', 'o', 'o', 'b', 'a', 'r'].reduce((o, e) => (o[e] = (o[e] || 0) + 1, o), {});
    // Object {f: 1, o: 2, b: 1, a: 1, r: 1}
    

    Please note the arrow notation functions I've used exploit the comma operator to return what I want, more traditionally you might write the function as e.g. followed by evolution to my examples

    function (o, e) {
        o[e] = Math.pow(e, 2);
        return o;
    }
    // same as
    function (o, e) {
        return o[e] = Math.pow(e, 2), o;
    }
    // similar to
    (o, e) => {
        return o[e] = Math.pow(e, 2), o;
    }
    // same as
    (o, e) => (o[e] = Math.pow(e, 2), o);
    

提交回复
热议问题