如何将同一行和同列的值相加,并将结果做成另一个数组(可以是一维的)
Array [
[ 1, 1, 0, 1 ],
[ 1, 1, 1, 1 ],
[ 1, 1, 1, 1 ],
[ 1, 1, 0, 1 ]
]
var res = []; //the 1D array to hold the sums
var hArr = [
[ 1, 1, 0, 1 ],
[ 1, 1, 1, 1 ],
[ 1, 1, 1, 1 ],
[ 1, 1, 0, 1 ]
]; //your array
var vArr = []; //Now lets create an array of arrays with the columns of hArr
for (var j=0; j<hArr[0].length; j++) {
var temp = [];
for (var i=0; i<hArr.length; i++) {
temp.push(hArr[i][j]);
}
vArr.push(temp);
}
//sum all the element in the line - Vertically and Horizontally
function SumVH (hInd, vInd) {
var sum = 0;
//add horizontal elements
for(var i=0; i<hArr[hInd].length; i++) {
sum += hArr[hInd][i];
}
//add vertical elements
for(var i=0; i<vArr[vInd].length; i++) {
sum += vArr[vInd][i];
}
//console.log("hInd="+hInd+" vInd="+vInd+" Sum="+sum);
return sum;
}
// go through the main array and get result
var sumR = 0;
//sum of each row
for (var i=0; i<hArr.length; i++) {
for (var j=0; j<hArr[i].length; j++) {
sumR = SumVH(i,j) - (2 * hArr[i][j]);
res.push(sumR);
}
}
请现在检查。变量res
保存结果
对于我上面写的数组,我想要的结果数组是7,7,5,7,8,8,6、8、8、8、6、8、7、7、5、7
现在上面的代码不计算总和中的数字本身。但是要得到您的评论结果,请替换这一行
sumR = SumVH(i,j) - (2 * hArr[i][j]);
sumR = SumVH(i,j);
谢谢。