VBScript: Array Functions - Arrays
(Page 2 of 6 )
Arrays are similar to variables, except where variables hold a value, arrays hold many values. You can think of a variable as a file folder, and an array as a file cabinet. Here is how we declare an array and assign values to it:
<html>
<body>
<script type="text/vbscript">
Dim cow(3)
cow(0) = "Moo "
cow(1) = "Went "
cow(2) = "the "
cow(3) = "cow"
document.write(cow(0))
</script>
</body>
</html>
The above code would result in:
Moo
This is because we told the program to write out the first value in the array, which was moo. You will note that when we Dimmed the array we called "cow," and we put the number 3 in parentheses. This sets the amount of elements, or values, we are storing in the array. I know I know...there are four values in the array, so why did we type three? We do this because array element indexes (the position of the data) begin at 0.
If we had written Dim cow(2), there would be three values, etc.
If we wanted to print out all of the values in the array, we would have to use a For Loop; we will cover this in a later tutorial in more depth. For now, check out the example shown below:
<html>
<body>
<script type="text/vbscript">
Dim cow(3)
cow(0) = "Moo "
cow(1) = "Went "
cow(2) = "the "
cow(3) = "cow"
For Each present In cow
document.write(present)
document.write("<br /><br />")
Next
</script>
</body>
</html>
This would result in the follow being printed to your monitor:
Moo
Went
the
cow
Note that if we had not inserted the <br /> tags, it would have printed...
Moo Went the cow
Lifetime of Variables
A variable's scope is its lifetime, or how long the variable is able to be used. If you put a variable inside a procedure (more on this later), it is only available inside that procedure and when the program exits the procedure, the variable is destroyed. This is known as a local variable. It cannot be used by any other procedures in the program.
A variable declared outside of a procedure is available to the entire program and only dies when the page is closed.
Next: Multi-Dimensional Arrays >>
More Windows Scripting Articles
More By James Payne