如何使用 reduce 计算对象数组的长度?

How can I calculate the length of an array of objects with reduce?

我有这个简单的函数,我只是想获取这个对象数组的长度。例如,在下面的情况下,我想 return 3 。我可以使用 .length(),但我想使用 reduce 方法探索更多内容。

function getSum(data) {
  const totalNum = data.reduce((sum, a) => sum + a.id, 0);
  return totalNum
}

console.log(getSum([
  {id: 'ddd6929eac', isComplete: true},
  {id: 'a1dd9fbd0', isComplete: true},
  {id: 'afa8ee064', isComplete: false}
]))

非常感谢:)

您可以为数组中的每一项添加一个。

function getSum(data) {
    return data.reduce((sum, a) => sum + 1, 0);
}

const
    data = [{ id: 'ddd6929eac', isComplete: true }, { id: 'a1dd9fbd0', isComplete: true }, { id: 'afa8ee064', isComplete: false }];

console.log(getSum(data));

那么 data.length 相当于:

data.reduce(sum => sum + 1, 0);

但我不明白你为什么要这样做,除非你试图排除空白值。

只需添加索引即可:

const totalNum = data.reduce((sum, a, index) => index+1);