What is causing the malfunction in this JavaScript date array?

I'm encountering an issue with my array of dates where they all end up being the same date when I try to retrieve them.

var paydates = new Array();
var i;
var firstDate = new Date();
firstDate.setFullYear(2010, 11, 26); //setting the initial date as 12/26/10

for (i=0; i < 200; i++) //adding 200 dates to the array
{
    paydates[i] = firstDate;
    firstDate.setDate(firstDate.getDate()+14); //incrementing the date by 14 days
    document.write("1st: " + i + ":" + paydates[i] + "<br />");
    //dates are displayed correctly here
}

//when attempting to retrieve the dates:
for (i=0; i < 200; i++)
{
    document.write("2nd: " + i + ":" + paydates[i] + "<br />");
    //this shows 200 instances of the same date
}

I'm struggling to figure out what's causing this issue. Any help would be appreciated.

Thank you

Answer №1

Within your loop, you are currently setting paydates[i] to reference the same value as firstDate for all 200 iterations. This means that by the end of the loop, all entries in the paydates array will be pointing to the last firstDate in the loop.

To address this issue, it would be more efficient to create a new instance of Date in each iteration and then assign it to the respective index in the paydates array.

Additionally, I noticed that the initial date in your example is not 12/26/2010 as stated, but rather 1/9/2011. Whether this is an oversight or intentional, it's important to ensure that the first firstDate aligns with the date used to initialize the array of dates.

You can view a simplified and functional example in this JSFiddle. Below is the basic code snippet from the provided fiddle:

var paydates = []; // new array
var firstDate = new Date(2010, 11, 26); // initial date

for (var i = 0; i < 200; i++) {
    paydates.push(new Date(firstDate.getTime()));
    firstDate.setDate(firstDate.getDate() + 14); // increment by 14 days
}

Answer №2

Make sure to update your initial loop with the following code snippet:

var temp;

for (i=0; i < 200; i++) //inserting 200 dates into our array
{
    temp = new Date(firstDate.getTime());
    paydates[i] = temp;
    firstDate.setDate(firstDate.getDate()+14); //adding 14 days
    document.write("1st: " + i + ":" + paydates[i] + "<br />");
}

The issue arose from storing a reference to the same firstDate object in each array index.

Answer №3

To assign each element in the array with an individual date, you need to create a new Date object based on firstDate.

Instead:

paydates[i] = firstDate;
firstDate.setDate(firstDate.getDate()+14); //add 14 days

write:

paydates[i] = new Date( firstDate.setDate(firstDate.getDate()+14));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unravel intricate JSON data and display it in a Material-UI table

How to convert the complex JSON data provided below into a material-ui table similar to the example shown. Each row may contain either a single value or multiple rows in a single box. I have attempted to display the data in 2 columns only, but need help wi ...

Issues with routing in NodeJS Express causing routes to not be called

I've been working on setting up a basic REST API using nodeJS. However, I am facing an issue where none of the endpoints are being called when I try to access them. Can someone guide me on what changes I need to make in order to get it working properl ...

CSS Code Failing to Adjust Inner Components Width in Variable Table

I'm facing an issue while trying to create an excel-style table using HTML and CSS. The problem arises when I attempt to have a varying number of columns in different rows, as the table exceeds the border limit and expands on its own. My goal is to re ...

Why am I not receiving recommendations for the data types of a function parameter when there are multiple variations available?

I'm currently navigating a JavaScript codebase that utilizes Sequelize models with documented types specified in TypeScript declaration files (.d.ts). Within my code, I am utilizing model.update() to modify certain properties on the object: To replic ...

Compatibility issues between Sinon, Require, and Backbone causing errors

Currently, I am following a tutorial on how to test Backbone applications using Jasmine and Sinon. I am attempting to stub out an object, and here is the code I have so far: define(function(require) { var sinon = require('sinon'); beforeEach ...

Angular Fire: The $on method is missing and causing an error stating that undefined is not a function

I am currently attempting to log my Firebase data to the console, but I keep encountering an error stating undefined is not a function. Below is the full error message: TypeError: undefined is not a function at Object.childAdded (http://localhost:9000/scr ...

What could be the reason for the GET method being executed after the DELETE method in ExpressJS?

Whenever I trigger the DELETE method in my Express app, it seems that the GET method is automatically invoked right after. This results in an error within my Angular code stating that it expects an object but receives an array instead. Why is the GET meth ...

Invalid component exception: The element type is not valid in React Native

In my React Native App.js file, I have included the following code snippet import { StatusBar } from 'expo-status-bar'; import React, { useRef } from 'react'; import { StyleSheet, Text, View, Canvas } from 'react-native'; impo ...

Why is my custom 404 page failing to load after building my Next.js application?

I recently set up a custom 404 page for my Next.js app and wanted to test it locally before deploying to the server. To do this, I used the "serve" package to host the project on my local machine. However, when I tried navigating to a non-existent page, th ...

I am struggling to grasp the flow of this code execution

Hi there, I just started my journey in JavaScript learning about two weeks ago. I would really appreciate it if someone could walk me through the execution steps of the code provided below. function sort(nums) { function minIndex(left, right) { ...

Send the form via ajax

I am in the process of creating a unique application for my university, which is essentially a social network. One key feature I need to implement is the ability for users to add comments, which involves inserting a row into a specific database. To achieve ...

``Why is it that the JavaScript code is unable to find the maximum or minimum sum? Let's

function calculateMinMaxSums(arr) { // Custom code implementation let max = Math.max(...arr); let min = Math.min(...arr); let minsum = 0; let maxsum = 0; for (let x in arr) { if (arr[x] != max) { minsum += arr[x]; }; if (arr[x ...

The proper method for developing Vue components that are dependent on the parent build tools

In my experience, this issue might also arise in other frameworks with plugin/component ecosystems that rely on specific build tools (such as React components with JSX). While Vue serves as my use-case. Having developed numerous Vue components as single . ...

Establish a timeout period for ajax requests using jQuery

$.ajax({ url: "test.html", error: function(){ //do something }, success: function(){ //do something } }); At times, the success function performs well, but sometimes it does not. How can I add a timeout to this ajax re ...

How to eliminate the "br" tags automatically inserted after each paragraph in TinyMCE version 6

I have been trying to work with TinyMCE version 6 and I am struggling to prevent the addition of <br> after each paragraph. Whenever I insert a line of text and press enter, a new paragraph is created but there is always a <br> added between t ...

Show Zeroes in Front of Input Numbers

I am working with two input fields that represent hours and minutes separately. <input type="number" min="0" max="24" step="1" value="00" class="hours"> <input type="number" min="0" max="0.60" step="0.01" value="00" class="minutes"> This se ...

JavaScript and CSS animations out of sync in terms of timing

I've been encountering some issues. I have an array containing 5 lines of text that change with a timer, but it seems that the css timer animation might not be synced properly or my @keyframes slidesdown setup could be incorrect. The delay between te ...

What sets apart ajax calls from getJSON requests?

I am encountering an issue with my Web.API app being served from the URL http://server/application. When I try to pull data from the servers using a GET request on the client side, I am facing unexpected behavior. The following code snippet works as expec ...

Using jQuery combogrid to automatically target and populate input box upon row selection

I have implemented combogrid functionality from https://github.com/powderblue/jquery-combogrid to display suggestions while typing. $(".stresses").combogrid({ url: '/index/stresssearch', debug: true, colModel: [{'col ...

How can I incorporate JSON data retrieved from my backend server into the content of Tabs in a ReactJS application, utilizing either the map() or forEach() method

I need help assigning a key from an object to each tab using a loop in order to navigate to its content when clicked on. I attempted to use map() but it didn't work, so I'm looking for guidance as I am new to React. Below is the code. Any assist ...