Using the reduce function to return an array

后端 未结 6 1735
一向
一向 2020-12-13 17:36

Why is it that when I want to use the push function inside the reduce function to return a new array I get an error. However, when I use the concat method inside the reduce

6条回答
  •  旧巷少年郎
    2020-12-13 18:21

    Just for completeness, and for the next person who happens on this question, what you're doing is typically achieved with map which, as stated in the docs

    map calls a provided callback function once for each element in an array, in order, and constructs a new array from the results

    Contrast that with the description of reduce:

    The reduce() method applies a function against an accumulator and each value of the array (from left-to-right) to reduce it to a single value.

    (Emphasis mine) So you see, although you can manipulate reduce to return a new array, it's general usage is to reduce an array to a single value.

    So for your code this would be:

    var store = [0,1,2,3,4];
    
    var stored = store.map(function(pV){
      console.log("pv: ", pV);
      return pV;
    });
    

    Much simpler than trying to reconstruct a new array using either push or concat within a reduce function.

提交回复
热议问题