Creating variables with increasing names can be done by using a loop in the

I'm having trouble figuring out how to approach this issue.

Currently, I have a variable set up to store an object:

var myobject = new object();

Everything is working fine; the name of the variable is 'my object' and it contains a new object.

If I need 10 variables, I would have to manually create 10 variable names like so:

var myobject1 = new object();
var myobject2 = new object();
var myobject3 = new object();
var myobject4 = new object();
... and so on

Now, I want to automate the process by incrementing the name of the variable (not the content) using a counter. This way, regardless of how many new objects I need, the name will change in an incremental fashion. Unfortunately, JavaScript doesn't seem to support this directly.

I've tried to come up with a logical solution, but I'm struggling with how to actually increment the variable name:

//global variables
var counter=0;
var tempname;

function makeplentyofobj(){

    if (temp name)
        tempname= new object(); //this should make myobjectN
    else
        myobject= new object(); //this makes myobject1
    counter ++;
    tempname ='myobject'+counter; //this makes a name for the next object)
}

When I run this code, the compiler assigns the new object to myobject, increments the counter to 1, and stores the string 'myobject1' in tempname. If I call the function a second time, the counter is now 1 and tempname holds 'myobject1'. This is the desired name for the next variable. However, since tempname is not empty, the else condition is triggered, leading to the conversion of its content from a string to an object.

Instead, what I truly want is to generate a new variable name that increments with each new object creation, such as:

myobject1=new object();
myobject2= new object();
...

Is there a way to achieve this in JavaScript?

EDIT:

Thank you for the response; I understand that this question may be similar to others, but I put effort into explaining my thought process. The next time, I'll try to simplify it more.

Answer №1

To solve issues like this, it's common practice to store objects in an array. This method simplifies the process of storing and retrieving objects.

var objArray = [];
objArray.push(new item());
objArray.push(new item());
objArray.push(new item());
objArray.push(new item());

Alternatively, you can place them directly in the initial declaration:

var objArray = [new item(), new item(), new item(), new item()];

If you simply need generic objects, it can be as straightforward as this:

var objArray = [{}, {}, {}, {}, {}];

Now, referencing a specific element is just a matter of:

var obj = objArray[n];

Remember that arrays start with index 0, so the first object would be at objArray[0].

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

Is there a way for me to implement this code to achieve the functionality shown in the demo link

$('select').change(function() { var sum = 0; var sum = parseInt($('select[name="bathrooms"]').val() * 25) + parseInt($('select[name="bedrooms"]').val() * 8); $("#sum").html(sum); }); <script src="https://ajax.googleap ...

Is it possible for me to retrieve a variable that is contained within a function?

I have extracted data from 2 separate JSON files and now I am looking to divide one by the other. How can this be achieved? Specifically, I aim to divide the 'sugString' with the 'htmlString'. Following this operation, I want to insert ...

What is the best way to rephrase a sentence that contains a double negative

Figuring out how to negate a condition often requires hours of trial and error to avoid breaking anything. Is there any method for negating conditions other than relying on intuition? For instance: //x and y are whole numbers !((x<9) && (y&l ...

Issue detected in the SeleniumLibrary Input Text function while being used within an if/else block

I am encountering an issue with my RobotFramework code. I am attempting to implement an If/ELSE statement and test some functionalities, but when I define the Keyword, I receive the error: "Keyword 'SeleniumLibrary.Input Text' expected 2 argumen ...

Tips for implementing a settimeout function in a VUEJS script

I'm currently working on my first Vue.js application and I'm facing an issue with the initial data upload in the script. After modifying the data received from a database call, I encounter an error during the page's initial load which resolv ...

The Jquery instructions were not executed

Enjoy your day! I have recently downloaded the latest compressed version of jQuery from a lesson site here (Download the compressed, production jQuery 3.6.0) After that, in my HTML document, I included it like this: <head> <meta charset = &qu ...

Veracode Scan finds vulnerability in jQuery html method with Improper Neutralization of Script-Related HTML Tags in a Web Page error

Veracode has flagged the issue Improper Neutralization of Script-Related HTML Tags in a Web Page (Basic XSS) within the following line of code. $('#SummaryDiv').html(data); $.ajax({ url: 'Target_URL', type: &a ...

Gradual appearance animation upon webpage load

I am attempting to create a fading effect on my homepage that is consistent every time it loads. Unfortunately, the current script I have only seems to work sporadically. The code I am currently using sets the fade effect on the html element since applyi ...

Creating a mapping strategy from API call to parameters in getStaticPaths

I am attempting to map parameters in Next.js within the context of getStaticPaths, but I am facing issues with it not functioning as expected. The current setup appears to be working without any problems. https://i.stack.imgur.com/LeupH.png The problem a ...

"Seamless responsiveness in design with jQuery, but encountering compatibility issues

My usage of jQuery is quite basic to ensure that elements are properly positioned when they are moved: function ipad() { var width = jQuery(window).width(); if (width < 1200 && width >= 768){ //if tablet jQuery('.mobbut').css(&apo ...

Shadowing jQuery variables involves declaring a new variable with the

There seems to be an unusual pattern used in jQuery: var jQuery = (function() { // This local copy of jQuery is defined within a closure var jQuery = function( selector, context ) { ... return jQuery; })(); Why was this approach chosen? Instead of exp ...

What could be the reason that my Javascript function is not displaying in the HTML document?

I'm currently working on developing an HTML page that displays random quotes by Mark Twain. The function and array of quotes are set up in a separate Javascript file which is linked to the main HTML document. However, I am facing an issue where the ou ...

How do I retrieve the NodesValue from the childNodes in an HTML tag?

<p title="The test paragraph">This example demonstrates some <b>HTML content that may be<br>present</b> in your file</p> txt=document.getElementsByTagName("p")[0].childNodes[0].nodeValue; alert("<p>The text from the in ...

Having trouble accessing variables from the dotenv file in a NextJS project

Recently, I started using Next.js and ran into a bit of trouble. Here's the issue: When I'm in the connectToMongo function, my variable is coming through just fine. However, when I switch over to Main/index.tsx, my process.env appears as an emp ...

Saving an array to a text file with a new line delimiter can easily be achieved using Types

I have an array of plain strings that I need to save to a text file. However, I'm encountering an issue where the strings are being saved as comma separated values instead of new lines. Here is the data I currently have: https://i.sstatic.net/r3XVr.j ...

Reverting Vue Draggable Components to Their Original Position Upon Dropping Them

In my Vue 3 project, I'm implementing vuedraggable to enable element reordering within an expansion panel. However, I've encountered an issue where the dragged elements revert to their original positions upon release. This behavior suggests that ...

Received an error while using an Express router: "Unable to access property 'caseSensitive' of undefined."

javaScriptCode app.js const express = require('express') const app = express() const {route} = require('./routes/route') app.use(express.static('./public')); app.use(express.json()); app.use(express.urlencoded()); app.use(rout ...

Illuminate the nodes as I sketch the link in GOJS

I've been attempting to outline all potential nodes when creating a new connection, but haven't had much luck. My goal is to accomplish something along these lines: https://i.sstatic.net/R6jbV.png I experimented with event listeners, bu ...

Utilizing Horizontal Navigation to Showcase Content (JavaScript)

I'm using the Flickity CSS library to create a horizontal scrolling navigation bar. I've customized the carousel template so that when a cell is selected, it snaps to the center of the bar. The carousel has 5 cells named 'slide 1', &apo ...

Assigning a new classification to the primary object in the evolving array of objects

I'm working with an element that loops through all the objects using v-for and has a CSS class named top-class{}... I need to dynamically add the top-class to the first object (object[0]) and update it based on changes, removing the old top-class in t ...