Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

273
Views
Why JavaScript array length return undefined when loop in matrix (2D array)

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)
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!