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

145
Visualizações
Value of array is changing with value of object

When I put an object into array using push method and then change the value of the object, the value of the object in the array also changes. How to prevent it?

function onLoad() {
    let array = []
    let object = {}
    object[1] = [1,2]
    array.push(object)
    object[1] = [1,3]
    console.log(array)
}

onLoad();

I would like the code console [{1,2}] but it will console [{1,3}].

Would anyone know how to fix this?

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

0

In JavaScript, Complex data types(Objects and arrays) are copied by reference whereas primitive data types(Strings, Numbers, and Boolean) are copied by value

Simply put , Pass by reference will not create a copy instead refer to the same memory. So original objects and arrays will be changed

Copy by value will create a copy of the value and hence original value will not be changed

function change(array1){

array1[0] = "changed";

}

var original = ["original"]
change(original)

console.log(original)


function changePrimitive(input) {
  input = "changed"

}

var original = "original"


changePrimitive(original)


console.log(original);

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