【问题标题】:What's a clean way to use an object literal to track several (unknown) counts?使用对象文字来跟踪几个(未知)计数的干净方法是什么?
【发布时间】:2019-07-29 08:37:50
【问题描述】:

给定以下代码,变量counts 计算函数functionThatGivesSomeKnownOrUnknownStatus 给出每个状态的次数。

const counts = {};

for (let i = 0; i < 100; i++) {
    const status = functionThatGivesSomeKnownOrUnknownStatus();

    counts[status] = counts[status] ? counts[status] + 1 : 1;
}

我不喜欢的部分是这条线counts[status] = counts[status] ? counts[status] + 1 : 1;,有没有办法让它更短更简单/更少冗余/更干净? 这是一个节点脚本,因此欢迎使用 ES6/7 解决方案。

一种方法是初始化 counts 文字,其中键已设置为 0,但我不知道该函数可以给出的状态。


尽量让标题简洁明了,如果可以改进,请随时编辑。

【问题讨论】:

  • counts[status] = (counts[status] || 0) + 1 节省了一次重复。
  • 更多语义的可能方法是使用值为 0 的default dict
  • (不过,不要像该问题的最佳答案那样使用代理实现默认字典。在Map 之上执行此操作要干净得多。)

标签: javascript algorithm optimization object-literal


【解决方案1】:

正如@Ry 所说,我最终使用了这个解决方案:

counts[status] = (counts[status] || 0) + 1;

代码内部:

const counts = {};

for (let i = 0; i < 100; i++) {
    const status = functionThatGivesSomeKnownOrUnknownStatus();

    counts[status] = (counts[status] || 0) + 1;
}

【讨论】:

    猜你喜欢
    • 2020-06-28
    • 2015-12-22
    • 1970-01-01
    • 2021-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-27
    • 2011-01-01
    相关资源
    最近更新 更多