简体   繁体   English

如果数组为空,JavaScript reduce返回null

[英]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
});

fiddle 小提琴

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

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