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

68
Visualizações
Javascript array.push changes some elements already in array

I am trying to add to an array, the array at the end should be > [0] (today) Name:Day1 Date:Fri June 10...

> [0] (today) Name:Day1 Date:Fri June 10... 
> [1] (today) Name:Day1+2 Date:Sun June 12... 

> [0] (today) Name:Day1 Date:Fri June 10... 
> [1] (today) Name:Day1+2 Date:Sun June 12...
> [2] (today) Name:Day1+3Date:Mon June 13...

The link with my debug session is:

But instead, the Date: changes for each array element, and is the last date to be pushed

> [0] Day1 - Fri Jun 10 2022 10:13:15 GMT-0700 (Pacific Daylight Time)

> [0] Day1 - Sun Jun 12 2022 10:13:15 GMT-0700 (Pacific Daylight Time)
> [1] Day1+2 - Sun Jun 12 2022 10:13:15 GMT-0700 (Pacific Daylight Time)

[0] Day1 - Mon Jun 13 2022 10:13:15 GMT-0700 (Pacific Daylight Time)
[1] Day1+2 - Mon Jun 13 2022 10:13:15 GMT-0700 (Pacific Daylight Time)
[2] Day1+3 - Mon Jun 13 2022 10:13:15 GMT-0700 (Pacific Daylight Time)

If anyone could explain this to me, I would be appreciative. I am fairly new to JS, so please be kind.

// globals
var TodaysDate;
var holidays = [];

function ShowHolidays() {
  console.log(holidays);
  for (let i = 0; i < holidays.length; i++) {
    console.log("[" + i + "] " + holidays[i].name + " - " + holidays[i].date);
  }
}

function AJSTEST() {
  TodaysDate = new Date();
  holidays.push({ name: "Day1", date: TodaysDate });
  ShowHolidays();
  debugger;

  var AD = TodaysDate;
  AD.setDate(AD.getDate() + 2);
  debugger;
  holidays.push({ name: "Day1+2", date: AD });
  ShowHolidays();
  AD.setDate(AD.getDate() + 1);
  holidays.push({ name: "Day1+3", date: AD });
  ShowHolidays();
  debugger;
}

AJSTEST();

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

0

What you have come across is the age old problem (which isn't really a problem, once you understand it it becomes more of a tool than a hinderance) of pass-by-reference (as opposed to pass-by-value, like you believe should be happening).

To get to the root of it, objects (basically everything you have to use the new keyword to create) are stored differently than items like ints, because they are so big. Ints are so small that when you do something like the example below, it doesnt take up a lot of storage so it passes the value of x into y and now they are separate fields with separate values

let x = 1
let y = x
x += 1

However, like I said, Date is an object. Because objects can take up a lot of space in storage, they are pass by reference. That means we just pass around the address in memory to all the variables/methods where you would like to use it.

Long story short, what you have created at the end of you method is a long list of 3 references all pointing to the same object, not 3 separate objects. So everytime you do AD.setDate(AD.getDate() + n); you are manipulating the object that AD points to, and because all the items in your array also point to the same address in memory, they reflect that same change.

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