JavaScript chooses to start pushing elements into index 1 rather than the traditional index 0

I'm currently facing an issue with a JavaScript variable that I am trying to initialize within another function using a for loop:

var test = {
    det: [{x: -1, y: -1}]
};

for (var i = 0; i < 4; i++) {
        test.det.push({x:10+i, y:10});
}

console.log(test.det);

Despite my efforts, when I attempt to access test.det[0], I still see -1 & -1 as the values โ€‹โ€‹of x & y. The first set of values pushed remain at index 1. It appears there is a shift in all indices but the reason behind this behavior eludes me.

Answer โ„–1

Array#push is used to add an additional item after the current last item in an array. To reinitialize, simply use assignment =:

var test = {
  det: [{x: -1, y: -1}]
};
  
for (var i = 0; i < 4; i++) {
  test.det[i] = ({x:10+i, y:10});
}

console.log(test);

Alternatively, you can clear the array and then utilize Array#push:

var test = {
  det: []
};

for (var i = 0; i < 4; i++) {
  test.det.push({x:10+i, y:10});
}

console.log(test);

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

Tips for retrieving the final value of a designated id within an array using JavaScript

One challenge I'm facing is storing row values in an array during an onkeyup event. Sometimes, the array ends up storing duplicate rows with different quantities and totals but the same ID. How can I modify my approach to only save the most recent set ...

User management functionality integrated into an AngularJS MVC skeleton project

Searching for an AngularJS project to get started with a basic MVC structure that includes user management, sign up and sign in UI, possibly utilizing CSS Bootstrap. Any recommendations or suggestions appreciated! Here are some nice ones I came across tha ...

Exploring the capabilities of NEXTJS for retrieving data from the server

When trying to retrieve data from the nextjs server on the front end, there is an issue with the code following the fetch() function inside the onSubmit() function. Check out the /test page for more details. pages/test const onSubmit = (data) => { ...

What is the best method for placing an element above all other elements on a page, regardless of the layout or styles being used?

I want to create a sticky button that remains fixed on the page regardless of its content and styles. The button should always be displayed on top of other elements, without relying on specific z-index values or pre-existing structures. This solution must ...

Retrieving error messages and status codes using Laravel and JWT authentication

One of the challenges I'm facing is implementing JWT Auth in my Laravel + Vue SPA. When checking the credentials in my Controller, the code looks like this: try { if (!$token = JWTAuth::attempt($credentials)) { return response()- ...

Putting Text Inside a Video Player in HTML

Is there a way to insert text, like a Logo, into my video player? https://i.sstatic.net/CZ6Rp.png I would appreciate any help on how to achieve this. Thank you. <video width="320" height="240" controls src="video/flashtrailer.mp4"> Your browser ...

exchange information among distinct domains

Two distinct services are operating on separate machines, resulting in different URLs for each service. The user initially accesses the front end of the first service. Upon clicking a button on this service, the user is directed to another front end servi ...

Trapped in the JavaScript Checkbox Filter Maze

After successfully creating a javascript-only filter, I have hit a roadblock and could really use some assistance. The filter is divided into "days" and "events". When a user clicks on a day or multiple days, the events for those selected days are displa ...

Should loaders be utilized in an Angular application?

Webpack configuration allows the use of various loaders, such as file-loader, html-loader, css-loader, json-loader, raw-loader, style-loader, to-string-loader, url-loader, and awesome-typescript-loader. Does Angular have built-in knowledge of loaders with ...

Is there a way for me to move a user from one room to another room?

My friend and I both have our own rooms in a session. When I want to send him a message, I need to switch his room to the same one where I am. This is the code snippet for creating my own room with static sessions: socket.on('chat-in', function ...

Unable to Access Browser Page

After printing out the URL in the console, I encountered an issue while trying to retrieve it using browser.get(). The error message displayed is as follows: Failed: Parameter 'url' must be a string, not object. Failed: Parameter 'url&apo ...

How can I pull the account creation date stored in MongoDB and display it using Handlebars?

Currently in my development, I am utilizing MongoDB, NodeJS, and Handlebars. My challenge is to convert the user.id into a timestamp and then display this timestamp on my HTML page. At present, I can display the user.id by using {{ user.id }} in my code, ...

Confirmed the validation of an input that falls outside the parameters of the ReactiveForms model

Check out this StackBlitz example In my Angular application, I am utilizing a Reactive form with 3 inputs, each having its own validation. Additionally, there is an input that exists outside of the form within its own component, also with its own reactive ...

Modifying paragraph content with JavaScript based on selected radio button values and troubleshooting the onclick event not triggering

I am working on implementing a language selection feature on my website where users can choose between English and Spanish. The idea is to have two radio buttons, one for each language, and a button. When the button is clicked, the text of the paragraphs s ...

Is the background image slowly disappearing?

Instead of using the background property for a background image, I have opted for a different style. Here is how I implemented it: <div id="bg"> <img id="bgChange" src="image/image.jpg" /> </div> This is the corresponding CSS code: ...

Search for URLs using both www and non-www, as well as both http and https, with the jQuery.g

I am currently using jQuery to search through a JSON string in order to find the matching URL and extract all data associated with that object. The URL is fetched using var url = window.location.href; However, this returns Within the JSON string, the U ...

Having trouble with the menu toggle button on Bootstrap 4?

When using Bootstrap 4, the breadcrumb button may not function properly when the header becomes responsive. I have ensured that Bootstrap 4 CSS and JS are included in the project. Please assist me in resolving this issue. Code: .navbar { height:100 ...

What steps do I need to take to link my form with Ajax and successfully submit it?

Here is my HTML code: {% extends 'base.html' %} {% block content %} <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Create a Recipe ...

Is it possible to "preload" an image using JavaScript in order to utilize it as a CSS background-image?

Is it possible to pre-load images into a web page using Javascript in order to use them as CSS background images without experiencing any delay due to requests or uploads? If it is possible, how can this be achieved? ...

Prevent webpage from jumping to the top when clicking on an editable Angular xeditable field within a ng-repeat

Every time I click on an xeditable field within my form that is generated by using ng-repeat, the form automatically scrolls to the top. <form editable-form name="myxedit"> <fieldset ng-repeat="shop in myModel.shops track by $index"&g ...