[英]JavaScript reduce returns null if array is empty
I need the count of my objects in the array based on their type. 我需要根据对象的类型对数组中的对象进行计数。 I don't know what I'm missing here, but this is what I do:
我不知道我在这里缺少什么,但这是我要做的:
myCounts = (myArray || []).reduce(function _countMembersByType(counts, member) {
return counts[member.type === productType.GROUP ? 'groupCount' : 'individualCount']++;
}, {groupCount: 0 , individualCount: 0});
When myArray
has members, myCounts
will be null
. 当
myArray
具有成员时, myCounts
将为null
。 Otherwise, it will be an object as myCounts: {"groupCount":0,"individualCount":0}
as I would expect. 否则,它将是我所期望的
myCounts: {"groupCount":0,"individualCount":0}
对象myCounts: {"groupCount":0,"individualCount":0}
。
I'm new to JS and would appreciate any help! 我是JS新手,不胜感激!
Your returning the result of plus 1'ing, so in the next iteration, previous or counts
will be a number not your base object. 您返回加1'ing的结果,因此在下一次迭代中,previous或
counts
将是一个数字,而不是您的基础对象。
You need to return the whole object. 您需要返回整个对象。
myCounts = (myArray || []).reduce(function _countMembersByType(counts, member) {
counts[member.type === productType.GROUP ? 'groupCount' : 'individualCount']++;
return counts;
}, {
groupCount: 0,
individualCount: 0
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.