在将 forEach 和 Reduce 映射到映射对象时遇到问题

当与对象值一起使用时,此方法适用于对象。但是,如何使其在地图对象上工作呢?


const one = new Map ();

one.set ('part1', {section1: 1, section2: 'one'});

one.set ('part2', {section1: 8, section2: 'eight'});

one.set ('part3', {section1: 5, section2: 'five'});


one.forEach(x => console.log(x.section1));


let temp1 = one.forEach(x => x.section1);

console.log(temp1);


let temp2 = one.forEach(x => x.section1).reduce((sum, cur) => sum + cur);

console.log(temp2);


千万里不及你
浏览 135回答 2
2回答

开满天机

该函数返回未定义,因此您无法调用该函数 reduce。forEach此外,你不需要调用函数,用一个reduce就好了。Array.prototype.mapconst one = new Map ();one.set ('part1', {section1: 1, section2: 'one'});one.set ('part2', {section1: 8, section2: 'eight'});one.set ('part3', {section1: 5, section2: 'five'});let temp2 = Array.from(one.values()).reduce((sum, {section1: cur}) => sum + cur, 0);console.log(temp2);

慕丝7291255

forEach 返回 ,您需要使用 来获取数组中的 值来调用它。undefinedArray.mapsection1reduce但问题是你没有财产。幸运的是,我们.Map.mapvaluesvalues() 方法返回一个新的 Iterator 对象,该对象包含 Map 对象中按插入顺序排列的每个元素的值。因此,我使用over迭代器在中获取一个可以运行的数组。...[].mapconst one = new Map ();one.set ('part1', {section1: 1, section2: 'one'});one.set ('part2', {section1: 8, section2: 'eight'});one.set ('part3', {section1: 5, section2: 'five'});let temp = [...one.values()].map(x => x.section1).reduce((sum, cur) => sum + cur);console.log(temp);或者,您甚至不需要函数 当您将值转换为数组时,可以直接调用mapMapreduceconst one = new Map ();one.set ('part1', {section1: 1, section2: 'one'});one.set ('part2', {section1: 8, section2: 'eight'});one.set ('part3', {section1: 5, section2: 'five'});let tempAlt = [...one.values()].reduce((sum, {section1: cur}) => sum + cur, 0);console.log(tempAlt);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript