Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Question about WHILE/FOR Loops

Status
Not open for further replies.

mdude85

Technical User
Joined
May 24, 2006
Messages
4
Location
US
Say I am writing a code like so:

Var[0] = 0
Var[1] = 1
Var[2] = 2

And I want to output the variables with a while loop so that they are output in a document.write(Var+'<br>') but that they stop outputting depending on the number in the Var[] brackets IF the number is NOT static -- that is the user can choose to add to Var[] (Var[3], Var[4]) but doesn't need to update the while loop (while (i<...). Is there any way for the script to determine the numbers inside the brackets by itself and then break once that number has been reached? Thanks.
 
1. You shouldn't name your variable "Var" - var is a reserved keyword in javascript and could cause problems. It's probably better to choose a more descriptive variable name depending on what it is they are storing.

2. Every array has a .length value, this determines how many elements are in the array. If you wanted to output your array from above you'd do it like this:

Code:
<script type="text/javascript">

var myArray = new Array();
myArray[0] = 0;
myArray[1] = 1;
myArray[2] = 2;

for (var i = 0; i < myArray[!].length[/!]; i++) {
   document.write("value in element " + i + ": " + myArray[i] + "<br>");
}
</script>

-kaht

[small]How spicy would you like your chang sauce? Oh man... I have no idea what's goin' on right now...[/small]
[banghead]
 
Thanks, the .length value is a really big help. However, when I run my script, the value corresponding to myArray[0] is left off (only the values in [1] and [2] are printed). If I start i = 0, shouldn't the [0] value be printed? Thanks.
 
Oops, nevermind, I think I fixed it. I removed the i++ right after my document.write in the for loop that I had included from another test code. I appreciate your help!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top