Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

274
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda