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

98
Visualizações
Push element in an empty array

I have an empty array:

const timeArray = []
const a = new Date(startTime_minTime)
const b = new Date(startTime_maxTime)
const disabledValueStart = new Date(maxStart)

// where startTime_minTime and startTime_maxTime are only two dates (date and time) and maxStart is the last value

Date.prototype.addHours = function (h) {
  this.setTime(this.getTime() + h * 60 * 30 * 1000)
  return this
}

//  Now I'm trying to do a while to populate the array 
while (a <= b) {
  timeArray.push(a)
  if (a !== disabledValueStart) {
    a.addHours(1)
  }
}

The problem is that my array has only the last value repeated for the number of elements that should populate it, how do I add one element at a time, so that I have them all at the end and not just the same repeated value?

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

0

You are pushing the same date (a) to the array, over and over. Clone the date and push the clone. That way each item in the array is a different date.

Here is a working snippet. The key is timeArray.push(new Date(a)).

const timeArray = []
const a = new Date()
const b = new Date(a.getTime()+60*60*24*1000)
const disabledValueStart = new Date(a.getTime()-60*60*24*1000)

Date.prototype.addHours = function (h) {
  this.setTime(this.getTime() + h * 60 * 30 * 1000)
  return this
}

while (a <= b) {
  timeArray.push(new Date(a)) // here is the important change
  if (a !== disabledValueStart) {
    a.addHours(1)
  }
}

console.log(timeArray)

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