error encountered when working with date arrays in JavaScript

I find myself perplexed by this particular issue.

Although the following code snippet appears to function correctly, it exhibits some peculiar behavior.

var tmpcurdte = eval(dataSource[i].startDate);
tmpcurdte.setDate(tmpcurdte.getDate() + 1);

while (tmpcurdte < tmpenddte) {
  console.log("block date: " + tmpcurdte);
  blockdayarray[blockdayarray.length] = tmpcurdte;
  console.log("blockdayarray: " + blockdayarray);
  tmpcurdte.setDate(tmpcurdte.getDate() + 1);
}

Output

block date :Sat Nov 12 2016 00:00:00 GMT+0100 (CET)
blockdayarray :**Sat Nov 12** 2016 00:00:00 GMT+0100 (CET)
block date :Sat Dec 31 2016 00:00:00 GMT+0100 (CET)
blockdayarray :**Sun Nov 13** 2016 00:00:00 GMT+0100 (CET),**Sat Dec 31** 2016 00:00:00 GMT+0100 (CET)
block date :Sun Jan 01 2017 00:00:00 GMT+0100 (CET)
blockdayarray :Sun Nov 13 2016 00:00:00 GMT+0100 (CET),**Sun Jan 01 2017** 00:00:00 GMT+0100 (CET),**Sun Jan 01 2017** 00:00:00 GMT+0100 (CET)
block date :Sat Feb 04 2017 00:00:00 GMT+0100 (CET)
blockdayarray :Sun Nov 13 2016 00:00:00 GMT+0100 (CET),Mon Jan 02 2017 00:00:00 GMT+0100 (CET),**Mon Jan 02 2017** 00:00:00 GMT+0100 (CET),Sat Feb 04 2017 00:00:00 GMT+0100 (CET)

It's interesting to note that the date in the array changes when a new one is added. I'm in need of assistance or an explanation on this matter. Can anyone provide insight?

Answer №1

The reason for this issue is caused by continuously adding the same `Date` object to the array and modifying its state.

To resolve this, you should create a fresh `Date` object for the following day:

var tmpcurdte = eval(dataSource[i].startDate);
tmpcurdte.setDate(tmpcurdte.getDate()+1);

while (tmpcurdte < tmpenddte) {
    console.log("block date :" + tmpcurdte);
    blockdayarray[blockdayarray.length]=tmpcurdte;
    console.log("blockdayarray :" + blockdayarray);
    tmpcurdte = new Date(tmpcurdte.getTime());     // ***
    tmpcurdte.setDate(tmpcurdte.getDate() + 1);
}

On a side note, the use of `eval` in your code raises some concerns. There is likely a more efficient and secure method to achieve the same functionality without using `eval`.

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

The default export of Nuxt, referred to as 'mod', could not be located

Using Nuxt with Typescript, I have created a custom component as shown below: <template> <div class="field"> <label class="label" v-if="typeof label !== 'undefined'">{{ label }}</label> <div class=" ...

What are some strategies for ensuring that Plotly JS can adapt its height and width to fit the entire div dynamically, without relying on fixed pixel dimensions?

Is there a way to ensure that Plotly automatically adjusts to the size of the container #myDiv without any noticeable delay when the top button is clicked? This code snippet demonstrates a high delay: var z = [], steps = [], i; for (i = 0; i < 500; i+ ...

Submitting forms that contain files using jQuery and AJAX

Despite searching through numerous questions on this topic, I have yet to find a solution to my specific issue. My objective is to successfully submit an entire form, potentially containing files as well. The code I currently have is not working: $(target ...

Practice window.performance.getEntriesByType with a mock function

I am facing an issue in my component where I need to check if the page is reloaded and redirect to another page. Here is the code snippet I am using: useEffect(() => { //this will prevent users from accidentally refreshing / closing tab window.o ...

Using JavaScript to save coordinates as a 2D Vector Object

Which option is optimal for both memory usage and calculation speed? new Float32Array(2); new Float64Array(2); {x: 0, y: 0}; [0, 0]; It's clear that option 1 uses less memory than option 2, but what about speed? Are calculations faster with 32 bits ...

What is the best way to initiate a function upon each page load?

(Apologies in advance for any English mistakes) Hello everyone, I am currently developing a simple Chrome extension to edit certain graphics and text fields on a website (Freshdesk) that cannot be modified directly on the site due to proprietary code. ...

Issue encountered while attempting to parse JSON data

I've been dealing with JSON data in Django view and parsing it in JavaScript to extract the necessary information. This is a snippet from my view.py file (Django) ibms = [] for i in range(2, 5): ibm = Mapa(i, wsMapa) ibms.append(ibm.__dict__) ...

Error: Unable to locate npm package

I am currently working on an Angular application that was created using Grunt and relies on Bower and NPM. Recently, I attempted to install an npm module locally. The installation resulted in the files being stored in the main application directory under ...

Using jQuery to display items from GitHub API in a custom unordered list format

Attempting to access data from the GitHub API using jQuery (AJAX) and display it on a static webpage. Here are the HTML and JS code snippets: $(document).ready(function(){ $.ajax({ url: 'https://api.github.com/re ...

What is the best way to coordinate text and photos within Bootstrap?

Currently, I am working on a bootstrap website that features a slideshow with 3 photos. The jQuery function responsible for this is as follows: $(function () { $.vegas('slideshow', { backgrounds: [{ src: 'img/ph1.jpg ...

"An error occurred: Attempting to access properties of an undefined object (specifically 'foundTicket'). While the getTickets() function, which fetches data from MongoDB using Mongoose, is working fine, the getTicketById()

I recently started working with next.js and I'm following a project tutorial by a YouTuber. Here is the link to my code: https://github.com/Fanguiee/ticketing-app/tree/edit-existing-item or you can also read below. Thank you in advance :) Screenshot: ...

Obtain a byte array from an AngularJs controller

In my Angular controller, I am working with a byte array. When the download button is clicked in the view, I want to trigger the browser's download/saveAs dialog with 'report.pdf' as the pre-populated filename and PDF as the file type. After ...

Is there a way to ensure that the vertical scrollbar remains visible within the viewport even when the horizontal content is overflowing?

On my webpage, I have multiple lists with separate headers at the top. The number of lists is dynamic and can overflow horizontally. When scrolling horizontally (X-scrolling), the entire page moves. However, when scrolling vertically within the lists, I wa ...

javascript dynamic content remains unaffected by ajax call

I'm a beginner with javascript and I am using a PHP variable to create links dynamically. Here is an example of how the variable is set: $addlink = '<button class="blueBtn btnSmall" id="current'.$product_id.'" onClick=addcart(' ...

Python is not formatting "n" and "k" with brackets as I intended

if __name__ == "__main__": d = len(sys.argv)>3 n = int(sys.argv[1]) k = int(sys.argv[2]) A = [] for i in range(n): A.append(i) if d: print("[{0} {1}]".format(n,k)) val = combinations(A, k) for i in val: print(i) I have implemented this pie ...

Changing the ng-src attribute with a custom service in an AngularJS application

Check out this Pluker I created for making image swapping easier. Currently, the images swap normally when coded in the controller. However, I am interested in utilizing custom services or factories to achieve the same functionality. Below is the code snip ...

Using D3 to create SVG elements in Next.js, the mouseenter event only triggers once

I'm currently developing a React Component that utilizes D3, however, I am facing an issue where the SVG circles are only triggered once. import React, { useEffect, useRef, useState } from 'react'; import * as d3 from 'd3'; import ...

Enhance the Angular KendoGrid excelExport feature with a custom column addition event

When utilizing the excelExport event in KendoGrid to modify certain column data before exporting it, is there a way to insert a new column between two existing columns? Here's the current code I'm using to manipulate dates. I would like to add a ...

An issue has been discovered with the Search function as JavaScript's Array.filter() and .map() methods are not functioning properly, resulting in

Currently, I'm working on integrating a search feature into my Flask application that will display the cities entered by users and are present in the JSON API results of a weather API. I am following a tutorial and have used a code similar to this: h ...

What is the best way to dynamically load content as it enters the viewport using JavaScript or jQuery?

I have implemented a stunning animation to the h1 element using a function, but now I want the animation to trigger only when the h1 element enters the viewport as the user scrolls down. Currently, the animation occurs as soon as the page is loaded, even ...