使用 reduce 函数来 return 一个数组

Using the reduce function to return an array

为什么当我想使用 reduce 函数中的 push 函数来 return 一个新数组时出现错误。但是,当我在 reduce 函数中使用 concat 方法时,它 return 是一个没有问题的新数组。

我想做的就是将一个数组传递给 reduce 函数,然后 return 传递一个相同的数组。

var store = [0,1,2,3,4];

var stored = store.reduce(function(pV,cV,cI){
  console.log("pv: ", pV);
  return pV.push(cV);
},[]);

这 return 是一个错误。但是当我使用 concat 时:

var store = [0,1,2,3,4];

var stored = store.reduce(function(pV,cV,cI){
  console.log("pv: ", pV);
  return pV.concat(cV);
},[]);

它return是同一个数组。

知道为什么吗?

Array.prototype.push方法returns数组的新长度。

Array.prototype.concat 方法将新元素插入数组,然后 returns 数组返回,以便可以进一步处理。这就是您需要对 reduce 做的事情:在下一次迭代中传递修改后的数组。

push returns数组的新长度。

你需要的是最初提供的数组

所以修改如下代码。

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 新数组结合了提供的数组元素和串联元素。所以它有效。

为了完整起见,对于遇到这个问题的下一个人,您所做的通常是通过 map 实现的,如文档中所述

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

对比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.

(强调我的)所以你看,虽然你 可以 操纵 reduce 到 return 一个新数组,但它的一般用法是减少一个数组到一个值。

因此对于您的代码,这将是:

var store = [0,1,2,3,4];

var stored = store.map(function(pV){
  console.log("pv: ", pV);
  return pV;
});

比尝试在 reduce 函数中使用 pushconcat 重建新数组要简单得多。

reduce() 如果您需要 return 一个包含每个迭代项的多个项的数组,

会很有用:

var inputs = media.reduce((passedArray, video) => {
    passedArray.push("-i");
    passedArray.push(video.filepath);
    return passedArray;
}, []);

此处用于为 FFmpeg 构建输入数组;

[{ name: "bob", filepath: "1.mp4" }, { name: "sue", filepath: "3.mp4" }]
=> ["-i", "1.mp4", "-i", "2.mp4]

你总是可以使用解构:

var store = [0,1,2,3,4];

var stored = store.reduce(function(pV,cV,cI){
  console.log("pv: ", pV);
  return [...pV, cV];
},[]);

console.log(stored);

我知道这是相同的答案,但我只是想表明使用 reduce (),也可以使用 ES6 将语法简化为一行代码:

var store = [0,1,2,3,4];

var stored = store.reduce((pV,cV) => [...pV, cV], []);

console.log(stored);