Nov 24, 2020 10:57 PM
I’m having trouble writing a script that creates new records (representing jobs) based on the following parameters:
I use a function to add jobs onto a stack, and call the function for each day of the week as required. My stack is defined outside the function as:
Let newJobs = ;
The new records created included a date field. That’s the problem. I can see my function looping through the dates correctly, and even pushing them onto the stack. But when everything is finish, every job on my stack has the final loop date. The same date. It was updated even after being added to the stack!
Function is:
function addJobs(opp,start, end, offset) {
let jobDate = new Date;
if (offset >= start.getDay()) {
let addDays = offset-start.getDay();
jobDate.setDate(start.getDate()+addDays);
}
else {
let addDays = 7+offset-start.getDay();
jobDate.setDate(start.getDate()+addDays);
}
for (let current = jobDate; current <= end; current.setDate(current.getDate()+7)) {
newJobs.push({
"oppLink": opp,
"newJobDate": current
});
)
}
}
Greatful if anyone can point out where I’m going wrong please, and/or point me to a sample doing the same sort of thing.
Solved! Go to Solution.
Nov 27, 2020 12:17 PM
It’s because date is mutable. You’re modifying the same object (current
) and assigning it to each job. You’d need to clone the current
date when adding it to newJobs
.
for (let current = jobDate; current <= end; current.setDate(current.getDate()+7)) {
newJobs.push({
"oppLink": opp,
"newJobDate": new Date(current.getTime())
});
}
Nov 27, 2020 12:17 PM
It’s because date is mutable. You’re modifying the same object (current
) and assigning it to each job. You’d need to clone the current
date when adding it to newJobs
.
for (let current = jobDate; current <= end; current.setDate(current.getDate()+7)) {
newJobs.push({
"oppLink": opp,
"newJobDate": new Date(current.getTime())
});
}
Dec 07, 2020 07:21 PM
Thanks @LukaszWiktor. Mutable – an important concept to know.
Dec 10, 2023 10:57 PM
Hi @LukaszWiktor. 3 years later and this advice helped me 🙂 Very much appreciated
Dec 11, 2023 12:32 AM
@Ricardo_da_Cost glad to know that my response what useful more than once. 😊