Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

195
Visualizações
JS: cannot assign to a nested array using nested for loop

I got a "TypeError: Cannot set property '0' of undefined" from this code snipet. Can anyone help me with this! Thank you very much

let array = [[]];
function generateField(width, height) {
    for (let i = 0; i < height; i++) {
        for (let j = 0; j < width; j++) {
            array[i][j] = Math.floor(Math.random() * 3);
        };
    };
    console.log(array);
    return array;
}

generateField(5, 5);
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Shouldn't the array declaration be : let array = [][] instead of let array = [[]] ?

about 4 years ago · Juan Pablo Isaza Relatório

0

You just need to initialize the array before trying to insert to the sencond level.

let array = [];
function generateField(width, height) {
    for (let i = 0; i < height; i++) {
        if(!array[i]) array[i] = [];
        for (let j = 0; j < width; j++) {
            array[i][j] = Math.floor(Math.random() * 3);
        };
    };
    console.log(array);
    return array;
}

generateField(5, 5);

about 4 years ago · Juan Pablo Isaza Relatório

0

Please consider these tips

  • Do not use array as a variable name because it could produce error in some browsers
  • Because Javascript Array is basically linked list there is no need to declare Array in this way let array = [[]]. For sure more suitable is creating new Array and push it to existing Array
  • Maybe declare let array = [[]] inside generateField function to make it more reusable because looking at your code I see you want function which creates new Array with n rows and m columns with random numbers and when let array = [[]] is outside your function will be modified every time when you call generateField

Working code below:

function generateField(width, height) {
    let rows = []
    for (let i = 0; i < height; i++) {
        let columns = []
        for (let j = 0; j < width; j++) {
            columns.push(Math.floor(Math.random() * 3))
        }
        rows.push(columns)
    };
    return [...rows] // create a copy of `Array` named `rows`
}

let matrix = generateField(3, 4)
console.log(matrix)

Output

Array(4) [ (3) […], (3) […], (3) […], (3) […] ]
​
0: Array(3) [ 0, 1, 2 ]
​
1: Array(3) [ 0, 2, 0 ]
​
2: Array(3) [ 1, 2, 2 ]
​
3: Array(3) [ 2, 1, 2 ]
​
length: 4
​
<prototype>: Array []
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda