Forum Moderators: open

Message Too Old, No Replies

Array and Looping

Basic Syntax Help

         

inveni0

6:01 pm on Oct 25, 2006 (gmt 0)

10+ Year Member



Can anyone help me to visualize how a basic loop through an array would work?

Imagine an array like:

Numbers[1] = 100
Numbers[2] = 250
Numbers[3] = 300

That will loop, doing a document.write of each value within the array?

Or, better yet, how do I count the number of records stored in an array?

Little_G

6:12 pm on Oct 25, 2006 (gmt 0)

10+ Year Member



Hi,

To return the number of elements in an array you use Numbers.length.

To loop you can use Javascript's version of the foreach statement:


for(i in Numbers){
document.write(Numbers[i]);
}

Andrew

inveni0

6:37 pm on Oct 25, 2006 (gmt 0)

10+ Year Member



Thank you!

Another question on topic;

Here is my loop:

for (var x = 0; x <= thumbURL.length; x++) {
document.thumb+x.src = thumbURL[x];
}

The 'document.thumb+x.src = thumbURL[x];' is where I'm having problems. It's not recognizing document.thumb+x How do I write that correctly?

Fotiman

6:56 pm on Oct 25, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month




for (var x = 0; x <= thumbURL.length; x++) {
document.thumb+x.src = thumbURL[x];
}

The 'document.thumb+x.src = thumbURL[x];' is where I'm having problems. It's not recognizing document.thumb+x How do I write that correctly?

Looks like you're trying to do an eval. As in:

eval("document.thumb" + x + ".src = " + thumbURL[x]);

eval takes a string and tries to execute it like code. I believe it's not great for performance, but should work.

Also, don't forget that arrays are zero indexed in JavaScript.

inveni0

7:22 pm on Oct 25, 2006 (gmt 0)

10+ Year Member



I plugged that in and got a "Expected ;" error. So, I changed it to

eval("document.thumb" + x + ".src = " + thumbURL[0] + ";");

and get the same thing. If I comment out this line of code, I get no errors, so I know something is fishy in this line.

inveni0

7:46 pm on Oct 25, 2006 (gmt 0)

10+ Year Member



Nevermind...I had to do this:

eval("document.thumb" + x).src = thumbURL[x];

I don't know if this is because the eval is in a function, but this is what it needed!

Thanks for the help!