从数组对象获取数字总和

时间:2020-07-22 07:02:18

标签: javascript

我想获取所有数组项的总和。

const arr = [{ a: 1 }, { b: 5 }, { c: 2 }];

const app = (arr) => {
    const r = arr.reduce((acc, nextValue) => {
        return acc[Object.keys(acc)] + nextValue[Object.keys(nextValue)]
    })
    return r
}
console.log(app(arr))

因此,最后我想得到:8 =总和:{ a: 1 }, { b: 5 }, { c: 2 }
问题:为什么我现在得到NaN

6 个答案:

答案 0 :(得分:2)

您需要一个起始值零和keys数组的第一个键,而不是整个数组。

求和直接带累加器。

const arr = [{ a: 1 }, { b: 5 }, { c: 2 }];
const app = (arr) => {
    const r = arr.reduce((acc, nextValue) => {
        return acc + nextValue[Object.keys(nextValue)[0]];
    }, 0);
    return r;
};

console.log(app(arr));

答案 1 :(得分:0)

您需要添加initialValue 0来减少

const app = (arr) => arr.reduce((acc, nextValue) => {
        return acc + Object.values(nextValue)[0]
    } ,0)
   
console.log(app(arr))

答案 2 :(得分:0)

最好指出您要从化简器返回一个数字,并将初始值类型数字作为函数中的第二个参数

const app = (arr) => {
        const r = arr.reduce((acc, nextValue) => {
          console.log(nextValue[Object.keys(nextValue)]);
          return acc + nextValue[Object.keys(nextValue)];
        }, 0);
        return r;
      };
      console.log(app(arr));

答案 3 :(得分:0)

这是如此简单,您很难。您需要值而不是键,并确保使用Number()函数

const arr = [{ a: 1 }, { b: 5 }, { c: 2 }];

const app = (arr) => {
    const r = arr.reduce((acc, nextValue) => {
        return acc += Number(Object.values(nextValue))
    },0)
    return r
}
console.log(app(arr))

答案 4 :(得分:0)

arr.map(obj => Object.values(obj))。flat()。reduce((acc,next)=> acc + = next)

const arr = [{ a: 1 }, { b: 5 }, { c: 2 }]

const arrayMap = arr.map(obj => Object.values(obj)).flat().reduce((acc, next) => acc += next)

console.log(arrayMap)

答案 5 :(得分:0)

首先让我们了解reduce是什么? 考虑以下自定义实现:

const arr = [{ a: 1 }, { b: 5 }, { c: 2 }];

const reduced = (array, instructionToCombine, buildingUpOn) => {
  for (let i = 0; i < array.length; i++) {
    buildingUpOn = instructionToCombine(buildingUpOn, array[i][Object.keys(array[i])]);
  }
  return buildingUpOn;
}

const instructionToCombine = (a, b) => a + b;

const ans = reduced(arr, instructionToCombine, 0);
console.log(ans)

现在,您了解了 JavaScript 默认reduce方法的工作原理。

您缺少initialValue(在我的实现中为buildingUpOn)。要知道,initialValue不是必需的参数,而是可选参数。但是,

如果未提供initialValue,则数组中的第一个元素为 用作初始累加器值,并跳过作为currentValue-MDN

但是您以其他方式对待,这就是为什么未获得预期答案的原因。 acc是第一次迭代的对象,但是在其余的迭代中,它是一个数字,但是您将其视为返回未定义的对象,并且将Numberundefined的总和返回{{1 }}。

如果您仍需要在不通过NaN 的情况下实现这一目标,则可以通过以下方式保留initialValue一个对象是很有可能的:

acc