需求:横向纵向都可以求和,剩余分数为100减去纵向之和
var arr = [
{
id: '张丹',
rowInfo: [
{ realScore: 12 },
{ realScore: 34 },
{ realScore: 0 },
{ realScore: 0 },
{ realScore: 0 },
],
},
{
id: '丽丽',
rowInfo: [
{ realScore: 0 },
{ realScore: 0 },
{ realScore: 0 },
{ realScore: 0 },
{ realScore: 12 },
],
},
];
var columnSums = [];
// 遍历数组的每个索引位置
for (var i = 0; i < arr[0].rowInfo.length; i++) {
var columnSum = 0;
// 遍历数组的每个对象,获取相同索引位置的元素,并求和
for (var j = 0; j < arr.length; j++) {
columnSum += arr[j].rowInfo[i].realScore;
}
columnSums.push(columnSum);
}
console.log("纵向求和结果:" + columnSums); // 输出:纵向求和结果:[12, 34, 0, 0, 12]