This section provides a tutorial example on how to use a 'For Each' statement to loop through all elements in an array.
In previous sections, we learned that a "For Each" statement can used to loop through all elements in an array quickly.
To show you how the "For Each" statement works, I wrote the following VBScript example, array_foreach.html:
<html>
<body>
<!-- array_foreach.html
- Copyright (c) 2015, HerongYang.com, All Rights Reserved.
-->
<pre>
<script language="vbscript">
' Creating a dynamic array
Dim aSite()
ReDim aSite(2)
aSite(0) = "yahoo"
aSite(1) = "netscape"
aSite(2) = "microsoft"
document.writeln("Is aSite an array? " & IsArray(aSite))
document.writeln("Lower bound of aPrime = " & LBound(aSite))
document.writeln("Upper bound of aPrime = " & UBound(aSite))
' Resizing the array
ReDim Preserve aSite(8)
aSite(8) = "ibm"
' Updating array elements
For Each sSite In aSite
sSite = sSite & ".com"
Next
' Retrieving array elements
document.writeln("Web sites:")
For Each sSite In aSite
document.writeln(" " & sSite )
Next
</script>
</pre>
</body>
</html>
Here is the output:
Is aSite an array? True
Lower bound of aPrime = 0
Upper bound of aPrime = 2
Web sites:
yahoo
netscape
microsoft
ibm
Noticed anything interesting? This VBScript example confirms that:
"For Each" statement creates a copy of the current element in the temporary variable
at each iteration. You can not update element values through this temporary variable.
My "Updating array elements" code block updated only the temporary variable, not array elements.