Your array example
isn't initialized anywhere. It should be like this:
var example = new Array();
example[1] = "one";
example[2] = "two";
example[3] = "three";
for (v = 1; v <= 3; v++) {
alert(example[v]);
}
This will make three separate alerts that say "one", then "two", then "three". If you want a single alert that says "one two three", you should do:
var example = new Array();
example[1] = "one";
example[2] = "two";
example[3] = "three";
var output = "";
for (v = 1; v <= 3; v++) {
output += " " + example[v];
}
alert(output);
In response to Chris' request for follow-up:
In that case you could nest the loops, but it would be much more efficient to generate the output string once and then loop to display it. Example:
var output = "";
// This variable just makes it happen 3 times, it no longer corresponds to the array size
for (numAlerts = 1; numAlerts <= 3; numAlerts ++) {
// This is the actual index for the array
for (v = 1; v <= example.length; v++) {
output += " " + example[v];
}
alert(output);
// Clean out the string or it will keep concatenating
output = "";
}
That example has computational cost of n^2 (technically m x n), because you are nesting the loops. To make 3 alerts, each with the concatenation of 3 array elements, would take 9 significant operations. The next example:
var output = "";
// This variable is once more for array size
for (v = 1; v <= example.length; v++) {
output += " " + example[v];
}
// This variable controls how many times the alert is printed
for (numAlerts = 1; numAlerts <= 3; numAlerts++) {
alert(output);
}
This one has computational cost 2n, reduced to n. In our example, 6 significant actions occur, 3 to concatenate the string, and 3 more to print it. 6 < 9, but not by much. However, imagine you have 300 items in the list, and want to print it 1000 times. Well, now 1300 << 300000.
One last note: in most languages, arrays are zero-based, so it would be example[0], [1], [2], etc.
I understand you matched example[1] = "one"
but it will make loops confusing if you start at 1. The standard for
cycle for an array is:
var example = ["zero", "one", "two", "three"];
for (i = 0; i < example.length; i++) {
action(example[i]);
}