Tengo una matriz vacía:
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) } }El problema es que mi matriz solo tiene el último valor repetido para la cantidad de elementos que deberían llenarla, ¿cómo agrego un elemento a la vez, para tenerlos todos al final y no solo el mismo valor repetido?
Está presionando la misma fecha ( a ) en la matriz, una y otra vez. Clonar la fecha y empujar el clon. De esa manera, cada elemento de la matriz es una fecha diferente.
Aquí hay un fragmento de trabajo. La clave es 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)