The JavaScript Diaries: Part 11

By Lee Underwood

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.

  1. The first line prints out a question to the screen.
  2. 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.
  3. 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:
    1. 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, 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.
    2. 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 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.

This article originally appeared on WebReference.com.

Page 6 of 6

Previous Page
1 2 3 4 5 6

  • Web Development Newsletter Signup

    Invalid email
    You have successfuly registered to our newsletter.
Thanks for your registration, follow us on our social networks to keep up-to-date