使用reduce函数返回一个数组 [英] Using the reduce function to return an array

查看:87
本文介绍了使用reduce函数返回一个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我想在reduce函数内部使用push函数返回一个新数组的时候报错.但是,当我在 reduce 函数中使用 concat 方法时,它返回一个没有问题的新数组.

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 function, it returns a new array with no problem.

我要做的就是将一个数组传递给 reduce 函数并返回相同的数组.

All I'm trying to do is pass an array to the reduce function and return the same array.

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

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

这会返回一个错误.但是当我使用 concat 时:

This returns an error. But when I use concat:

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

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

它返回相同的数组.

知道为什么吗?

推荐答案

push 返回数组的新长度.

您需要的是最初提供的数组.

What you need is the initially provided array.

因此将代码更改如下.

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 返回组合提供的数组元素和连接元素的新数组.所以它有效.

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

这篇关于使用reduce函数返回一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆