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

查看:135
本文介绍了使用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.

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

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天全站免登陆