views:

33

answers:

1

Hi,

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?

+5  A: 

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
    };
}
David Dorward
Can't upvote enough...
GlenCrawford
Appologies, I'm slightly unfamiliar with what you've done there.Presumably '[];' declares 'foo' as an array. And then inside the loop, does 'foo[i] = { EX1, EX2 };' create an array nested within the current array represented by 'i'?
Jack Roscoe
@Jack: Close. Inside the loop, a new object is being created for each iteration, with the attributes 'width' and 'height', and being assigned to foo[i]. So at the end, the array 'foo' contains a bunch of objects, each one containing those two attributes.
GlenCrawford
Ah I see, thanks for the explanation Glen.And of course thanks for the answer David.
Jack Roscoe