Procedures - Functions and Subroutines
Part:
1
2
3
4
5
6
(Continued from previous part...)
Here is the output:
Test 1: Swapping two literals by value
Before Sub: Apple | Orange
In Sub: Orange | Apple
After Sub: Apple | Orange
Test 2: Swapping two variables by value
Before Sub: Dog | Cat
In Sub: Cat | Dog
After Sub: Dog | Cat
Here are my comments about this example:
- Test 1 is useless.
- Test 2 shows that "ByVel" arguments will not bring any changes back to the calling code.
After the subroutine call, values in vFirst and vSecond have not been changed at all.
Passing Array as Arguments
As I mentioned earlier, arrays can also be passed as arguments. If an array is passed by reference,
the procedure is working on the same array as the calling code. If an array is passed by value,
the procedure is working on a independent copy of the array in the calling code.
Here is an example code of using array as an argument, function_reverse_array.html:
<html>
<body>
<!-- function_reverse_array.html
Copyright (c) 2006 by Dr. Herong Yang. http://www.herongyang.com/
-->
<pre>
<script language="vbscript">
document.writeln("")
document.writeln("Test 1: Reversing a data literal")
bOk = ReverseArray("Apple")
aPets = Array("Bird", "Cat", "Dog", "Fish", "Rabbit")
document.writeln("")
document.writeln("Test 2: Reversing an array")
document.writeln(" Before Sub: " & Join(aPets))
bOk = ReverseArray(aPets)
document.writeln(" After Sub: " & Join(aPets))
Function ReverseArray(ByRef aList)
If IsArray(aList) Then
iMin = LBound(aList)
iMax = UBound(aList)
For i=iMin to iMax\2
j = iMax - (i-iMin)
vTemp = aList(i)
aList(i) = aList(j)
aList(j) = vTemp
Next
ReverseArray = True
Else
document.writeln("Error: You are not giving an array.")
ReverseArray = False
End If
End Function
</script>
</pre>
</body>
</html>
Here is the output:
Test 1: Reversing a data literal
Error: You are not giving an array.
Test 2: Reversing an array
Before Sub: Bird Cat Dog Fish Rabbit
After Sub: Rabbit Fish Dog Cat Bird
My "ReverseArray" function worked perfectly. You can take it a utility function to your application.
(Continued on next part...)
Part:
1
2
3
4
5
6
|