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

522
Visualizações
Why my code to clone an array doesn't work JavaScript

So since JavaScript doesn't let you copy array using "=" I have to write this code. But it doesn't work

let arr = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
];
var arrclone = [];

for (let x = 0; x < arr.length; x++) {
  for (let y = 0; y < arr[x].length; y++) {
    arrclone[x][y] = arr[x][y];
  }
}
console.log(arrclone);

It said

arrclone[x][y] = arr[x][y];
                    ^
TypeError: Cannot set property '0' of undefined. 

How is it undefined both of them are already been declared. Sorry, I am a beginner sorry if my question seems stupid.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

When you start, each row of the array is empty. So initialise it to an empty row of array:

for (let x = 0; x < arr.length; x++) {
  // Use this...
  arrclone[x] = [];     // ========================> You missed this line.
  for (let y = 0; y < arr[x].length; y++) {
    arrclone[x][y] = arr[x][y];
  }
}

FYI, for the right approach, please use Array.slice() (but only for primitive values, see the problem here).

about 4 years ago · Juan Pablo Isaza Relatório

0

You should ideally be using Array.slice() for copying arrays:

let arr = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
];
var arrclone = arr.map(e => e.slice());
console.log(arrclone);

about 4 years ago · Juan Pablo Isaza Relatório

0

Javascript is not a language that makes copies on assignment. It uses references and stores them instead. Here you are literally just copying reference to the data instead of actual data. There are multiple ways to help you with this.

  1. The most simple way is to use var arrclone = JSON.parse(JSON.stringify(arr))

  2. We can also use array destructuring and it will look something like this: var arrclone = [...arr]

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