如何获取 ES6 Node JS Map 中所有值的总和

How to get sum of all values in ES6 Node JS Map

我的代码无法使用 Node JS 对所有值求和。有人可以帮忙修复吗?

VS 代码的错误是:

TypeError: undefined is not a function

let addInput = new Map( 
  {"key1":10},
  {"key2":5},
  {"key3":7},
  {"key4":17}
);

let sum = 0;

addInput.forEach((v) => {
  sum += v;
});

console.log(sum);

您必须创建 key-valueMap,您可以在此处使用 flatMap

const arr = [{ key1: 10 }, { key2: 5 }, { key3: 7 }, { key4: 17 }];
let addInput = new Map(arr.flatMap((o) => Object.entries(o)));

const arr = [{ key1: 10 }, { key2: 5 }, { key3: 7 }, { key4: 17 }];
let addInput = new Map(arr.flatMap((o) => Object.entries(o)));

let sum = 0;
addInput.forEach((v) => {
  sum += v;
});

console.log(sum);

我更愿意在此处使用 for..of 循环

const arr = [{ key1: 10 }, { key2: 5 }, { key3: 7 }, { key4: 17 }];
let addInput = new Map(arr.flatMap((o) => Object.entries(o)));

let sum = 0;
for (let [, v] of addInput) sum += v;

console.log(sum);

您可以使用 set 方法为新地图设置值:

 let addInput = new Map();
addInput.set("key1", 10);
addInput.set("key2", 5);
addInput.set("key3", 7);
addInput.set("key4", 12);