Do You Remember Algebra from School?
Do you remember algebra from school? x=5, y=6, z=x+yDo you remember that a letter (like x) could be used to hold a value (like 5), and that you could use the information above to calculate the value of z to be 11?
These letters are called variables, and variables can be used to hold values (x=5) or expressions (z=x+y).
VBScript Variables
As with algebra, VBScript variables are used to hold values or expressions.A variable can have a short name, like x, or a more descriptive name, like carname.
Rules for VBScript variable names:
- Must begin with a letter
- Cannot contain a period (.)
- Cannot exceed 255 characters
Declaring (Creating) VBScript Variables
Creating variables in VBScript is most often referred to as "declaring" variables.You can declare VBScript variables with the Dim, Public or the Private statement. Like this:
| Dim x Dim carname |
You can also declare variables by using its name in a script. Like this:
| carname="Volvo" |
If you misspell for example the "carname" variable to "carnime", the script will automatically create a new variable called "carnime". To prevent your script from doing this, you can use the Option Explicit statement. This statement forces you to declare all your variables with the dim, public or private statement.
Put the Option Explicit statement on the top of your script. Like this:
| Option Explicit Dim carname carname=some value |
Assigning Values to Variables
You assign a value to a variable like this:| carname="Volvo" x=10 |
Lifetime of Variables
How long a variable exists is its lifetime.When you declare a variable within a procedure, the variable can only be accessed within that procedure. When the procedure exits, the variable is destroyed. These variables are called local variables. You can have local variables with the same name in different procedures, because each is recognized only by the procedure in which it is declared.
If you declare a variable outside a procedure, all the procedures on your page can access it. The lifetime of these variables starts when they are declared, and ends when the page is closed.
VBScript Array Variables
An array variable is used to store multiple values in a single variable.In the following example, an array containing 3 elements is declared:
| Dim names(2) |
| names(0)="Tove" names(1)="Jani" names(2)="Stale" |
| mother=names(0) |
| Dim table(4,6) |
Example (IE Only)
<html><body>
<script type="text/vbscript">
Dim x(2,2)
x(0,0)="Volvo"
x(0,1)="BMW"
x(0,2)="Ford"
x(1,0)="Apple"
x(1,1)="Orange"
x(1,2)="Banana"
x(2,0)="Coke"
x(2,1)="Pepsi"
x(2,2)="Sprite"
for i=0 to 2
document.write("<p>")
for j=0 to 2
document.write(x(i,j) & "<br />")
next
document.write("</p>")
next
</script>
</body>
</html>
No comments:
Post a Comment