我的代碼無法使用 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);
uj5u.com熱心網友回復:
您必須創建一個Mapof key-value,您可以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);
uj5u.com熱心網友回復:
您可以使用set方法為新地圖設定值:
let addInput = new Map();
addInput.set("key1", 10);
addInput.set("key2", 5);
addInput.set("key3", 7);
addInput.set("key4", 12);
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/365434.html
標籤:javascript 节点.js ecmascript-6
下一篇:發送訂單給孩子
