The JavaScript Diaries: Part 11/Page 6
[previous]
The JavaScript Diaries: Part 11
Dynamic Arrays
Sometimes you won't know what data will be used in the array. One of the ways of dealing with that is to use a dynamic array. This allows the user to input the data and then let the script process it. The example below is rather simple but it's a good example of how this technique can be used to gather data.
document.write("What are your three favorite musical groups?<br>"); var favGroups = new Array(3); for (var i=0; i<3; i++) { var inputGroups=prompt("My favorite musical groups are: ", ""); favGroups[i] = inputGroups; document.write(i+1+". "+ favGroups[i]+"<br>"); }We could have added a validation routine that would make sure the prompt box was filled in on each pass (along with a few other things), but you get the idea. Let's break it down and see what's going on.
- The first line prints out a question to the screen.
- Then, we declared a variable named
favGroups
and initialized it with a reference to a new instance of an array. We also pre-set the size of the array for three elements. This will help in the loop that follows. - Next we began a loop using a prompt window to gather data. The prompt window is assigned to a variable named
inputGroups
. Basically, it works like this:- A prompt window opens with the statement,
My favorite musical groups are:
and then offers a box to gather the data. When the data is entered, theOK
button is pressed. This populates thefavGroups
array, which then uses the data in thedocument.write
statement listed on the next line. - The loop continues until all three elements are entered and sent to
the array which is in turn used for the
document.write
statement. (Notice I once again added "1" to the first "i
" in thedocument.write
statement so that the numbering will begin at "1." It doesn't increase the overall value of the variable "i
." That's done by the increment operator, "++
".)
- A prompt window opens with the statement,
Conclusion
That concludes our first installment in this series on arrays. Next time we'll look at some different types and see how they can be used to enhance to our scripts.
Continue on to "The JavaScript Diaries: Part 12"
[previous]
Created: November 24, 2005
URL: