[英]How to multiply object values in es6
確定所以我有一個填充了一個對象的變量,並且該對象具有鍵值對,現在是代碼!
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)
});
我試圖運行拋出對象並乘以值並將它們添加到新的區域數組!
您不需要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);
您可以破壞對象並乘以值。
var images = [{ height: 10, width: 30 }, { height: 20, width: 90 }, { height: 54, width: 32 }], areas = images.map(({ height, width }) => height * width); console.log(areas);
我建議你使用數組的map函數來完成它:不需要創建一個空數組並在其中推送值。
這是代碼:
const areas = images.map(({ height, width }) => height * width)
而已。
在回調的參數中我正在使用對象解構,你可以在這里查看: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
您的對象中沒有value
屬性,並且您已在箭頭函數中擁有可變image
,因此只需將其與image
的屬性height
和width
一起使用即可。 並且您在箭頭函數中不需要大括號:
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);
您可以根據兼容性需求使用不同的方法
var images = [ { height: 10, width: 30 }, { height: 20, width: 90 }, { height: 54, width: 32 } ] // For new browsers - ES6 support var areas1 = images.map(({height, width}) => height * width) console.log(areas1) // For older browsers - ES5 support // no destructuring, no arrow functions used var areas2 = [] images.forEach(function (i) { areas2.push(i.height * i.width) }) console.log(areas2) // For ancient browsers - ES3 support // no forEach method var areas3 = [] for (var i = 0; i < images.length; i++) { areas3.push(images[i].height * images[i].width) } console.log(areas3)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.