Here is my code but this array returns only the same elements, i am trying to create an array which contains 10 elements as the next mondays anyone know please help me
my code:
function getNextDayOfTheWeek(dayName, excludeToday = true, refDate = new Date()) {
const dayOfWeek = ["sun","mon","tue","wed","thu","fri","sat"]
.indexOf(dayName.slice(0,3).toLowerCase());
if (dayOfWeek < 0) return;
refDate.setHours(0,0,0,0);
refDate.setDate(refDate.getDate() !!excludeToday
(dayOfWeek 7 - refDate.getDay() - !!excludeToday) % 7);
return refDate;
}
let arr=[]
for(let i=0;i<10;i ){
arr.push(arr[i]=getNextDayOfTheWeek("Monday",false))
}
console.log(arr)
CodePudding user response:
getNextDayOfWeek
is being given the same inputs and so will have the same outputs.
You need to:
- Establish the base line date and pass it as the third parameter
- Pass the resulting date on the subsequent calls so that it advances
- Indicate that it should exclude the base line date if it matches the requested date
- Insert a
new Date
into the result array, because Dates are objects and thus passed by reference. If you don't do this, each call ofgetNextDayOfTheWeek
will be making changes to the same object stored in each position of the result array. - Note that your local time might cause the displayed date to appear to be before or after the expected date. You will likely need to decide how to account for local timezone (note that the result might show
Z
at the end of the time indicating UTC).
let arr=[]
let refDate = new Date()
for(let i=0;i<10;i ){
refDate = getNextDayOfTheWeek("Monday",false, refDate)
arr.push(refDate)
}
function getNextDayOfTheWeek(dayName, excludeToday = true, refDate = new Date()) {
const dayOfWeek = ["sun","mon","tue","wed","thu","fri","sat"]
.indexOf(dayName.slice(0,3).toLowerCase());
if (dayOfWeek < 0) return;
refDate.setHours(0,0,0,0);
refDate.setDate(refDate.getDate() !!excludeToday
(dayOfWeek 7 - refDate.getDay() - !!excludeToday) % 7);
return refDate;
}
let arr=[]
let refDate = new Date()
for(let i=0;i<10;i ){
refDate = getNextDayOfTheWeek("Monday", i > 0 ? true : false, refDate)
arr.push(new Date(refDate))
}
console.log(arr)