JavaScript - 在同一行和列中生成值的总和

时间:2015-07-10 10:34:21

标签: javascript arrays multidimensional-array

如何在同一行和列中创建值的总和,并生成另一个数组(可以是一维)。

Array [
    [ 1, 1, 0, 1 ],
    [ 1, 1, 1, 1 ],
    [ 1, 1, 1, 1 ],
    [ 1, 1, 0, 1 ]
]

1 个答案:

答案 0 :(得分:2)

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);

谢谢。