如何在es6中乘以对象值

Jim*_*ton 5 javascript foreach ecmascript-6

好的,所以我有一个充满对象的变量,该对象具有键值对,现在是代码!

var images = [
  { height: 10, width: 30 },
  { height: 20, width: 90 },
  { height: 54, width: 32 }
];
var areas = [];

//calculate the are of hte image 

images.forEach((image)=>{
    areas.push(images.height.value*images.width.value)
});
Run Code Online (Sandbox Code Playgroud)

我试图运行抛出对象并乘以值并将它们添加到新的区域数组中!

ade*_*neo 6

您不需要该value属性,并且您必须使用来自您正在迭代的内容的参数,即image在每次迭代中。

您可以使用Array.map将值直接返回到新数组,并且Array.reduce如果您想对这些值求和

var images = [
  { height: 10, width: 30 },
  { height: 20, width: 90 },
  { height: 54, width: 32 }
];

var areas = images.map( img => img.height * img.width);
var total = areas.reduce( (a,b) => (a+b) );

console.log(areas);
console.log(total);
Run Code Online (Sandbox Code Playgroud)


MrG*_*eek 0

您的对象中没有value属性,并且您的箭​​头函数中已经有了该变量image,因此只需将它与 的属性heightwidth一起使用image即可。而且箭头函数中不需要大括号:

var images = [
  { height: 10, width: 30 },
  { height: 20, width: 90 },
  { height: 54, width: 32 }
];
var areas = [];

//calculate the area of the image 

images.forEach((image)=>
    areas.push(image.height*image.width)
);
console.log(areas);
Run Code Online (Sandbox Code Playgroud)