...

View Full Version : Can I use loop increment number to reference a variable?



helpneeded22
10-01-2012, 09:47 AM
I have a large list of variables (which are arrays), all with the same variable name, but with a number behind it.

i.e.

item1
item2
item3

I want to create a loop that will display the item information, based on the incremented number.

i.e.

for (i=0;i<10;i++)

document.write(item1[0])

However in the above example I would like item1 to be item(i)

Is there any way to do this in javascript?

Philip M
10-01-2012, 10:00 AM
for (i=0; i<10; i++){
var c = ["item" + i]; // item0 to item9
document.write(c[0]);
}

All advice is supplied packaged by intellectual weight, and not by volume. Contents may settle slightly in transit.

Old Pedant
10-02-2012, 02:43 AM
I have a large list of variables (which are arrays), all with the same variable name, but with a number behind it.
item1
item2
item3


WHY?

Why not have an ARRAY OF ARRAYS:

So you would have (for example)


item[1][0], item[1][1], item[1][2], ...
and
item[2][0], item[2][1], item[2][2], ...
and
item[3][0], item[3][1], item[3][2], ...
and so on

Then there's no need for the (admittedly cute) trick that Philip had to pull.

Logic Ali
10-02-2012, 04:55 AM
for (i=0; i<10; i++){
var c = ["item" + i]; // item0 to item9
document.write(c[0]);
}

That assigns a single-element array holding a string. [] notation must be applied to a parent property, like window in the case of global variables.

All properties of my advice will remain unchanged; I don't drive a Transit.

xelawho
10-02-2012, 06:01 AM
while we're on the subject of cute...



<body>
<script>
var item1=[1,2,3];
var item2=[7,14,21];
var item3=[18,36,54];

str="";
for (i=1;i<4;i++){
str+="document.write(item"+i+"[0]+'<br>');"
}

var s = document.createElement('script');
s.text=str;
document.body.appendChild(s);

</script>

Philip M
10-02-2012, 08:39 AM
<script type = "text/javascript">

var item1=[1,2,3];
var item2=[7,14,21];
var item3=[18,36,54];

var numArrays = 3; // number of arrays item[x]

function displayArrayValues() {
for (var i=1; i<=numArrays; i++) {
var a = window["item"+i]; // array name
for (var j=0; j<a.length; j++) {
document.write(a[j] + "<br>");
}
document.write("<br>");
}

}

displayArrayValues();


</script>



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum