【问题标题】:Replace FOR to add all values in an array [duplicate]替换 FOR 以添加数组中的所有值 [重复]
【发布时间】:2019-08-14 12:59:59
【问题描述】:

我正在使用 Javascript,我有一个这样的数组:

counters: [
      { id: 1, value: 0 },
      { id: 2, value: 10 },
      { id: 3, value: 5 },
      { id: 4, value: 3 }
    ]

我想获得一个变量总计,其中包含计数器数组中每个值字段的总和。现在我在做:

Total() {
    let total = 0;
    for (let i = 0; i < counters.length; i++) {
      total += counters[i].value;
    }
    return total;   
}

即使这样可行,我也知道有更好的方法。我尝试了reduce 方法,但我无法得到我需要的东西。我该怎么做?

【问题讨论】:

    标签: javascript arrays


    【解决方案1】:

    您可以将destructured 值添加到Array#reduce

    var object = { counters: [{ id: 1, value: 0 }, { id: 2, value: 10 }, { id: 3, value: 5 }, { id: 4, value: 3 }] },
        sum = object.counters.reduce((s, { value }) => s + value, 0);
    
    console.log(sum);

    【讨论】:

      【解决方案2】:

      const  counters = [
             { id: 1, value: 0 },
             { id: 2, value: 10 },
             { id: 3, value: 5 },
             { id: 4, value: 3 }
           ]
           
       const total = counters.map(x => x.value).reduce((a,c) => a +c)
       
       console.log(total)
           
           

      map 你的数组只代表value 属性并使用reduce

       const total = counters.map(x => x.value).reduce((a,c) => a + c)
      

      【讨论】:

        【解决方案3】:

        你可以用reduce来做,只需传入一个默认值0:

        counters = [
               { id: 1, value: 0 },
               { id: 2, value: 10 },
               { id: 3, value: 5 },
               { id: 4, value: 3 }
             ]
             
        total = counters.reduce((accumulator, counter) => accumulator + counter.value, 0);
        
        console.log(total);

        【讨论】:

          【解决方案4】:

          最简单的方法是使用reduce方法 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce ;)

          const total = counters.reduce((acc, curr) =&gt; acc + curr.value, 0);

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2020-04-01
            • 2018-09-09
            • 1970-01-01
            • 1970-01-01
            • 2011-01-27
            相关资源
            最近更新 更多