【问题标题】:Get SUM of value in Array获取 Array 中值的 SUM
【发布时间】:2020-04-29 21:51:17
【问题描述】:

我想得到数组中值的总和。当我console.log(this.totalCount) 使用此代码时,我只会得到这样的

如何得到所有值的总和?

代码

return this.http
      .post('/media', reqBody)
      .pipe(
        map((res:IStatisticReponse) => res.data)
      ).subscribe(res => {
        this.items = res.map((r: any, i: number) => {
          r.color = this.colors[i]
          return r;
        });

        this.legendProgress = this.items.map(item => {
          return { label: item.label, color: item.color };
        });
        this.totalCount = this.items.map((item)=> item.mediaShare);
        console.log(this.totalCount)

        this.isLoading = false;
      });

【问题讨论】:

  • map() 方法创建了一个新数组,其中填充了在调用数组中的每个元素上调用提供的函数的结果。 所以你的代码必须是 this.totalCount.length我不知道你为什么使用空值的地图
  • @OnurGelmez 当我添加 this.items.length 时出现错误 (property) Array<any>.length: number Gets or sets the length of the array. This is a number one higher than the highest element defined in an array. This expression is not callable. Type 'Number' has no call signatures.ts(2349)
  • console.log(this.items) 的结果是什么?
  • 我猜,你应该说,你需要这些值的sum
  • 示例:totalCount = 2656 + 1987 + 1071

标签: angular typescript


【解决方案1】:

在您当前的实现中,您基本上遍历 items 数组中的所有项目并返回对象 mediaShare 属性。

this.totalCount = this.items.map((item)=> item.mediaShare); // => ["123", "345", ...]

你真正想做的是得到所有这些值的总和。 考虑到 totalCount 中的值现在是 strings 的集合,似乎包含一个数值,您可以执行以下操作:

this.totalCount = this.items.map((item)=> Number.parseInt(item.mediaShare)).reduce((acc, curr) => acc + curr, 0); // Or `parseFloat`, if your values might be of type float

阅读 Array.prototype.reduce 以了解其行为方式。

【讨论】:

  • 你的代码只显示这样265619871071 而不是值的总和
  • 我想要这样的`totalCount = 2656 + 1987 + 1071`
  • 这正是我给你的。我添加了另一个编辑,也许你在它之前检查了代码。请使用提供的最新解决方案再次测试。
【解决方案2】:

试试这个

let totalVal;
for(let i = 0; i < this.totalCount.length; i++) {
  totalVal = totalVal + parseInt(this.totalCount[i]);
}

【讨论】:

    猜你喜欢
    • 2020-01-11
    • 1970-01-01
    • 2021-11-29
    • 1970-01-01
    • 2018-09-22
    • 1970-01-01
    • 2020-10-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多