简体   繁体   English

减少空数组

[英]Reduce array of empty arrays

I'm trying to run a reduce function on an array on arrays. 我正在尝试在数组上的数组上运行reduce函数。 The arrays inside the array can be empty. 数组内部的数组可以为空。 So: [[], [], [], []].reduce((x, y) => x.length + y.length) does not work 因此:[[],[],[],[]]。reduce((x,y)=> x.length + y.length)不起作用

[[2, 3], [2, 3], [3, 5], [5, 6]].reduce((x, y) => x.length + y.length) doesn't seem to work either? [[2,3],[2,3],[3,5],[5,6]]。reduce((x,y)=> x.length + y.length)似乎也不起作用?

Am I missing something? 我想念什么吗?

The signature for the function you pass as the first argument to .reduce is 作为.reduce的第一个参数传递的函数的签名为

(accumulator, currentValue, currentIndex, array) => {...}

The second argument you can pass to reduce is the starting value for the accumulator. 您可以传递来reduce的第二个参数是累加器的起始值。

In your case, (x, y) => x.length + y.length is trying to get the length of the accumulator, named x , which will be undefined , and add it to the length of the first array in the parent array. 在您的情况下, (x, y) => x.length + y.length试图获取名为x的累加器的length ,它将是undefined ,并将其添加到父数组中第一个数组的length

When you try to add undefined to a number, you get NaN . 当您尝试将undefined添加到数字时,您会得到NaN

My guess is that you're trying to calculate the aggregate length of all the arrays in your parent array? 我的猜测是您要计算父数组中所有数组的总长度吗? If so, try this... 如果是这样,请尝试...

[[],[],[],[]].reduce((acc, array) => acc + array.length, 0)
// returns 0

[[2, 3], [2, 3], [3, 5], [5, 6]].reduce((acc, array) => acc + array.length, 0)
// returns 8

You could take a start value for Array#reduce . 您可以将Array#reduce用作起始值。

 var getLength = (r, x) => r + x.length, length0 = [[], [], [], []].reduce(getLength, 0), // ^ length1 = [[2, 3], [2, 3], [3, 5], [5, 6]].reduce(getLength, 0); // ^ console.log(length0); console.log(length1); 

Watch out because x.length and y.length will eventually turn into integers and integers don't have a length property. 请注意,因为x.length和y.length最终将变成整数,并且整数没有length属性。

You can do something like 你可以做类似的事情

(x, y) => x.length || x + y.length || y

So that if x.length exists, it gets used, otherwise just use the value of x 这样,如果存在x.length,它将被使用,否则只需使用x的值

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

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