Using the reduce function to return an array

后端 未结 6 1744
一向
一向 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:17

    push returns the new length of the array.

    What you need is the initially provided array.

    So change the code as below.

    var store = [0, 1, 2, 3, 4];
    
    var stored = store.reduce(function(pV, cV, cI){
      console.log("pv: ", pV);
      pV.push(cV);
      return pV; // *********  Important ******
    }, []);
    

    concat returns the new array combining the elements of the provided array and concatenated elements. so it works.

提交回复
热议问题