【问题标题】:Calculate values returned from loop计算从循环返回的值
【发布时间】:2021-01-15 02:54:36
【问题描述】:

我创建了需要返回适当长度项目的方法:

@Input() items: any[];

  calculateCount(type?: string | string[]): number {
    if (typeof type === 'object') {
      for (let value of type) {
        this.items && this.items.filter((item) => item.type === value).length;
      }
      //TODO: return sum of values from loop;
    }

    if (typeof type === 'string') {
      return this.items && this.items.filter((item) => item.type === value).length;
    }
    return this.items && this.items.length;
  }

但我需要建议如何从循环中返回值的总和。谢谢

【问题讨论】:

    标签: javascript angular typescript for-loop


    【解决方案1】:
    let total = loopitems.reduce((acc, val) => acc += val.itemToSumUp, 0);
    

    loopitems 是所有需要计数的项目。

    itemToSumUp 是您需要求和的属性(如果您需要整个对象,请不要使用 .xxx。)

    0 = 从零开始计数。

    【讨论】:

      【解决方案2】:

      我一直在寻找解决方案,并通过使用 .some() 方法而不是 for 循环计算找到了一个。 这是我所做的:

      calculateCount(type?: string | string[]): number {
      
          if (Array.isArray(type)) {
              return this.items && this.items.filter((item) => type.some((someType) => someType === item.type)).length;
          }
              
          if (typeof type === 'string') {
              return this.items && this.items.filter((item) => item.type === value).length;
          }
          return this.items && this.items.length;
      }
      

      我希望这会有所帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-11-09
        • 1970-01-01
        • 1970-01-01
        • 2016-07-20
        • 1970-01-01
        • 2023-03-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多