【问题标题】:How to iterate over objects in array and sum a property without iterating? [duplicate]如何迭代数组中的对象并对属性求和而不迭代? [复制]
【发布时间】:2018-01-05 07:35:00
【问题描述】:

是否可以将对象数组的所有 duration 值加起来而不进行迭代?

const data = [
  {
    duration: 10
    any: 'other fields'
  },
  {
    duration: 20
    any: 'other fields'
  }
]

结果应该是“30”。

let result = 0
data.forEach(d => {
  result = result + d.duration
})
console.log(result)

【问题讨论】:

  • 不,没有迭代就不可能迭代一个数组 - 顺便说一句,我建议使用 reduce ... let result = data.reduce((r, d) => r + d.duration, 0);
  • 不可能。一种有效的方法是使用 reduce developer.mozilla.org/en/docs/Web/JavaScript/Reference/…
  • 我相信量子计算机无需迭代就能解决这个问题。
  • 虽然尝试在不使用迭代的情况下进行迭代是不可行的概念,但可以使用递归而不是迭代来从数组的每个对象中提取指示的对象属性值并将这些值汇总。事实上,“...迭代只是递归(尾递归)的一个特例”(参见:ocf.berkeley.edu/~shidi/cs61a/wiki/Iteration_vs._recursion)。请参阅codepen.io/anon/pen/YxwdpR 的示例代码

标签: javascript


【解决方案1】:

如果没有迭代,您将无法完成此任务。 您可以使用 array#reduce ,它使用迭代。

const data = [
  {
    duration: 10,
    any: 'other fields'
  },
  {
    duration: 20,
    any: 'other fields'
  }
];

var result = data.reduce(
  (sum, obj) => sum + obj['duration'] 
  ,0
);

console.log(result)
.as-console-wrapper { max-height: 100% !important; top: 0; }

【讨论】:

    【解决方案2】:

    如果没有一些迭代,我不会工作,以获得指定属性的总和。

    您可以将Array#reduce 与回调一起使用,并且起始值为零。

    const data = [{ duration: 10, any: 'other fields' }, { duration: 20, any: 'other fields' }];
    let result = data.reduce((r, d) => r + d.duration, 0);
    
    console.log(result);

    【讨论】:

    • 效果很好,谢谢
    猜你喜欢
    • 2015-11-07
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多