简体   繁体   English

减少js - 减少到数组

[英]Reduce js - reduce to array

Can you tell me why that doesn't work and how to make it work, with a simple 'reduce' method?您能告诉我为什么这不起作用以及如何使用简单的“减少”方法使其起作用吗?

let newArray = array.reduce((acc,value,index) => index%2 ? acc[0]+=value: acc[1]+=value ,[0,0]);
console.log(newArray);
Output: Nan

'array' is just an array with numbers. 'array' 只是一个带有数字的数组。

Please don't create answers with some long and complex functions.请不要用一些冗长而复杂的函数来创建答案。 I want to make it as simple as it can be.我想让它尽可能简单。

I know that we can do this:我知道我们可以这样做:

let sum = [0,0];

array.map((value,index)=> index%2? sum[0]+=value : sum[1]+=value);
console.log(sum);

but I'm just curious, why that doesn't work.但我只是好奇,为什么这不起作用。

You aren't returning the accumulator ( acc ) from the function.您不会从 function 返回累加器 ( acc )。 You are returning the result of the assignment expression acc[0] += value which is just a number.您正在返回赋值表达式acc[0] += value的结果,它只是一个数字。 On the next iteration you try to index into that number.在下一次迭代中,您尝试索引该数字。 You can fix this using something like:您可以使用以下方法解决此问题:

 let array = [1, 2, 3, 4, 5] let newArray = array.reduce((acc,value,index) => (index % 2? acc[0] += value: acc[1] += value, acc),[0,0]) console.log(newArray);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM