Jack Roscoe
Jack Roscoe

Reputation: 4333

Is it possible to use an incremental value within a variable name whilst declaring it within a loop?

I'm creating function which will read different XML files each time that will contain different amounts of the same nodes.

I have already created a loop which stores the ID of each node into an array, and now I want to create variables for each array member which store attributes of the node with each ID.

Because the number of nodes will be different for every XML document my function reads, I cannot manually assign variables for the attributes of each node ID not knowing how many to assign, so I have created a loop which runs specific to the number of items I have stored in the array. Inside this loop I was hoping to have something like:

for (i=0; i<array.length; i++)
{
    var ID + i + width = exampleheight
    var ID + i + height = exampleheight
}

I know this doesn't work, but was trying to outline what I am looking to find out. Is it possible to use some kind of variable or random number when declaring a variable?

Upvotes: 0

Views: 117

Answers (1)

Quentin
Quentin

Reputation: 944441

Yes, but don't. It is ugly and prone to error. Programing languages usually have useful data structures, take advantage of them.

Use arrays and objects.

var foo = [];
for (i=0; i<array.length; i++)
{
    foo[i] = {
        width: example_width,
        height: example_height
    };
}

Upvotes: 5

Related Questions