0

I tried to create a 2D array to store the sum of another 2D array. When I ran this code it returned "Cannot read properties of undefined (reading 'length')". I know I should replace nums[i].length to nums[0].length to make code work. But why does a variable not work for getting array length?

Here are codes:

var nums=[[1,2,3],[4,5,6],[7,8,9]]

function MatrixArray() {
  MatrixArray.prototype.preSum = function (nums) {
    var preSumArray = new Array(nums.length +1).fill(0).map(()=>new Array(nums[0].length + 1).fill(0));
    for (var i = 1; i <= nums.length; i++) {
      for (var j = 1; j <= nums[i].length; j++) {
        preSumArray[i][j] =
          preSumArray[i][j - 1] +
          preSumArray[i - 1][j] -
          preSumArray[i - 1][j - 1] +
          nums[i - 1][j - 1];
      }
    }
    console.log(preSumArray);
  };
}

var result = new MatrixArray()
result.preSum(nums)
min gong
  • 56
  • 3

0 Answers0