| home / programming / javascript / diaries / 11 |
|
|
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.
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.inputGroups. Basically, it works like this:
My favorite musical groups are: and then offers a box to gather the data. When the data is entered, the OK button is pressed. This populates the favGroups array, which then uses the data in the document.write statement listed on the next line.document.write statement.
(Notice I once again added "1" to the first "i" in the document.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, "++".)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"
| home / programming / javascript / diaries / 11 |
Created: November 24, 2005
URL: