js 計算對象數組中某個屬性合計


js 計算對象數組中某個屬性合計

countTotal調用示例:

let arr = [
	{id: 0, price: 199.88},
	{id: 1, price: 299.88},
	{id: 2, price: 399.88}
];
console.log(countTotal(arr, 'price')); //899.64
//計算對象數組中某個屬性合計
function countTotal(arr, keyName) {
	let $total = 0;
	$total = arr.reduce(function (total, currentValue, currentIndex, arr){
	    return currentValue[keyName] ? (total + currentValue[keyName]) : total;
	}, 0);
	return $total;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM