将每列2d数组相乘并返回数组

时间:2015-11-25 17:51:39

标签: javascript arrays multiplication

这里是JS的新手。如何使用math.js或vanilla js返回一个数组,其中2d数组乘以每列。 2个数组的大小将始终相同。

[[2,2],
[2,4]]

结果是

[4,8]

我试过了:

adjustedrating = [[2,2],[2,4]]
var w = adjustedrating.length;

for (var i = 0, len = adjustedrating[0].length; i < len; i++) {
  var multiple = adjustedrating[0][i];
  for (var j = 0; j < w; j++) {
      multiple *= adjustedrating[j][i];

  }
  both.push(multiple);
};

1 个答案:

答案 0 :(得分:0)

您可以做的是遍历外部数组,并随时存储乘法结果。例如:

// The two dimensional array
var twoDimArray = [[2,2],
                   [2,4]];

// We'll say this is where your results will go. It will be the same length
//     as one of your inner arrays, and all values will start at 1
var results = [1,1];

// Loop through the 2D Array
for( var outerIndex = 0; outerIndex < twoDimArray.length; outerIndex++){
    // Loop through the currently selected inner array
    for( var innerIndex = 0; innerIndex < twoDimArray[outerIndex].length; innerIndex++){
        // Multiply appropriate result by the appropriate value
        results[innerIndex] *= twoDimArray[outerIndex][innerIndex];
    }
}

// Simply displays the results somewhere
document.getElementById('results').innerHTML = results;
<div id="results"></div>