Using the push method on a global object array will replace all existing values within the array

After researching various solutions to this issue, I have not been successful in implementing the commonly suggested fix. The variable evtList holds a collection of global objects labeled as "Event". Previous discussions advised creating a local object ("newEvent") within a loop, setting its properties, and then adding it to the global array. Despite following these steps, I have observed that modifying the newEvent object's elements results in all objects within the global array being updated with the same values before the addition operation. What am I overlooking here?

var i = 0;
var nextTime = new Date();

while (evtList[i].evtTime < dayEnd) {
    i++;
    var newEvent = new Event;
    var milliSecs = (evtList[i-1].evtTime).getTime() + gaussian(arrStations[0].mean, arrStations[0].stdDev);
    nextTime.setTime(milliSecs);
    newEvent = ({value: 1, station: 0, evtTime: nextTime});

    evtList.push(newEvent);
}

Answer â„–1

When working with JavaScript, it's important to note that the var keyword does not establish block-level scope, but rather function-level scope. This means that variables like newEvent are not limited to the for loop they are declared in, but rather belong to the function body or the global scope if not inside a function.

In your code, when you use push to add objects to your evtList, you run into an issue where all the evtTime properties reference the same Date object. As a result, any changes made to one evtTime affect all the others because they are essentially pointing to the same object.

To resolve this, you should create a new Date object for each of your objects as shown in the code snippet below:

var newEvent;
var milliSecs;
var nextTime;
var i = 0;

while (evtList[i].evtTime < dayEnd) {
  i++;
  nextTime = new Date;
  milliSecs = (evtList[i - 1].evtTime).getTime() + gaussian(arrStations[0].mean, arrStations[0].stdDev);
  nextTime.setTime(milliSecs);
  newEvent = ({
    value: 1,
    station: 0,
    evtTime: nextTime
  });

  evtList.push(newEvent);
}

Furthermore, it seems that the newEvent object pushed to evtList is not of the expected type Event because it is being overwritten by a plain JavaScript object. You can correct this by explicitly setting the properties of the Event object, as shown in the following code snippet:

newEvent.value = 1;
newEvent.station = 0;
newEvent.evtTime = nextTime;

Alternatively, you could pass these properties to your Event constructor for better organization and consistency in your code.

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

Utilize AngularJS to create a concealed input field

Currently utilizing angularjs, you can find the code at this link Desired Outcome: When the add button is clicked, I want the value of $scope.todotest to appear along with the text in the textbox. Issue Faced: Upon adding for the first time, the date d ...

Guide on dragging and dropping without losing the item, allowing for continuous drag and drop functionality

function allowDrop(ev) { ev.preventDefault(); } function drag(ev) { ev.dataTransfer.setData("text", ev.target.id); } function drop(ev) { ev.preventDefault(); var data = ev.dataTransfer.getData("text"); ev.target.appendChild(document.getElementB ...

Expand the HTML Template and Resize Children to Fit the Window

My software creates HTML email templates that typically range from 600px to 650px in width, but can sometimes be as wide as 900px. The templates have nested table elements for email clients, with all dimensions specified in fixed pixels rather than relativ ...

Why do confirm or alert boxes in Safari on Windows require a double click?

I'm currently working on a simple JavaScript example where I want to display an alert box when an HTML button is clicked in SAFARI. However, I've noticed that it requires a double click to make the alert disappear from the screen. Does anyone ha ...

Issues with PHP server handling JSON files

I'm having some trouble retrieving server data to display in a table on my iPhone. The process involves the standard flow of server - php_interface - iOS. Initially, I attempted to use an echo json_encode(array) setup, but ran into issues with populat ...

Encountering the 'navigator is not defined' error when attempting to generate a Next JS build

After developing a custom hook in Next JS to retrieve network online status using the JavaScript navigator.onLine property, everything seemed to work flawlessly on my local machine. However, upon running npm run build to compile the project, I encountered ...

Extract data from a CSV table stored in a variable using node.js

Currently, I am working on a node application that can potentially result in a CSV formatted table being stored in a variable. I am interested in converting this CSV data into a JSON format. I have explored various modules, but it appears that most of th ...

Sending multiple objects using Ajax and fetching them in PHP

I'm facing an issue with posting a form and an array to my PHP script. My current approach involves using the following code: var json_data = JSON.stringify(data_vendor); //array to be posted $.ajax({ url: &ap ...

The Rtk query function does not generate endpoints

Having trouble with code splitting in RTK-query, it's not working for me and I can't figure out why App.jsx import React from "react"; import { Provider } from "react-redux"; import store, { persistor } from "store" ...

Trouble arises when accessing GET form in php/Ajax

I am in the process of creating a dynamic website. At the top, I have an input form that, when submitted, should display the output from an asynchronous request to a PHP page using echo to show what was submitted. Unfortunately, it's not functioning ...

What is the best way to ensure that the input submit element is only visible after the input checkbox element has been checked?

For a school project, I am attempting to create a simulated reCAPTCHA box. Although my code is complete, I would like the functionality to submit your response from the input fields above only after selecting the reCAPTCHA checkbox. Upon researching, it ap ...

Tips for efficiently importing a file or folder that is valuable but not currently in use

I'm struggling to find any information about this particular case online. Perhaps someone here might have some insight. I keep getting a warning message saying 'FournisseursDb' is defined but never used no-unused-vars when I try to import t ...

Tips on organizing and designing buttons within a canvas

let canvas = document.getElementById("canvas"); let context = canvas.getContext("2d"); // for canvas size var window_width = window.innerWidth; var window_height = window.innerHeight; canvas.style.background="yellow" canvas.wid ...

React not displaying wrapped div

I am facing an issue with my render() function where the outer div is not rendering, but the inner ReactComponent is displaying. Here is a snippet of my code: return( <div style={{background: "black"}}> <[ReactComponent]> ...

Saving base64 encoded pdf on Safari

I am facing an issue with a POST call that returns a base64 PDF. The problem arises when trying to convert it to a Blob and download it using Safari browser. This method works perfectly in all other browsers. openPdf = () => { const sendObj = { ...

Module exists; however, command could not be located

I am experiencing an issue with the rimraf node module. Despite being able to access its folder within the node_modules directory, I am receiving errors indicating that the command for rimraf cannot be found. I have attempted to delete the entire node_mod ...

Google Chrome is unable to process Jquery JSON .each() function

My website has a simple chat application that is functioning well. It uses ajax to request data in this manner: $.ajax({ url: "fetch/"+CHAT_SESSION_ID+"/"+LAST_MESSAGE_ID, dataType: "json", cache: false, success: function(data) { if (data.session_ac ...

Guide to creating scroll-based animations for a Div element

I've been brainstorming ways to rotate a div as I scroll. My goal is to recreate the effect shown in this codepen. However, I'm struggling to implement scrolling functionality. What I envision is scrolling down causing the word Data to rotate in ...

Creating a specialized Angular directive for handling input of positive numbers

I am working on an application that requires a text field to only accept positive integers (no decimals, no negatives). The user should be restricted to entering values between 1 and 9999. <input type="text" min="0" max="99" number-mask=""> While s ...

Leveraging the CSS-Element-Queries Library for emulating the functionality of CSS media queries

Recently, I used a nifty CSS-Element-Queries tool to perform basic element manipulations that trigger whenever the window is resized. In simple terms, my goal was to dynamically adjust an element's attribute based on the current width of the window â ...