VBScript Tutorials - Herong's Tutorial Examples - v6.02, by Herong Yang
Creating a Copy of an Array
This section provides a tutorial example on how to create a copy of an array quickly with the array assignment statement.
How do you create a copy of an array? Of course, you can first declare an empty new array. Then copy all elements from the original array into the new array with a "For Each" loop. But that's too slow.
If you read previous sections, you know that the quickest way to copy an array is to use the array assignment statement:
scalar_variable = original_array_variable
The array assignment statement will automatically create a new array as a copy of the specified array for you. The receiving scalar variable will contain a reference to the new array, which will be a dynamic-size array regardless of the type of the original array.
To show you how to use an assignment to create a copy of an array, I wrote the following example, array_copy.html:
<html> <body> <!-- array_copy.html - Copyright (c) 1998 HerongYang.com. All Rights Reserved. --> <pre> <script language="vbscript"> aSite = Array("yahoo", "netscape", "microsoft") aTemp = aSite ReDim Preserve aTemp(3) aTemp(2) = aTemp(2) & ".com" aTemp(3) = "google.com" document.writeln("") document.writeln("The Original array:") document.writeln(" Lower bound: " & LBound(aSite)) document.writeln(" Upper bound: " & UBound(aSite)) document.writeln(" Elements:") For Each sSite In aSite document.writeln(" " & sSite ) Next document.writeln("") document.writeln("The second copy of the array:") document.writeln(" Lower bound: " & LBound(aTemp)) document.writeln(" Upper bound: " & UBound(aTemp)) For Each sSite In aTemp document.writeln(" " & sSite ) Next </script> </pre> </body> </html>
Here is the output:
The Original array: Lower bound: 0 Upper bound: 2 Elements: yahoo netscape microsoft The second copy of the array: Lower bound: 0 Upper bound: 3 yahoo netscape microsoft.com google.com
The output confirms that the assignment statement "aTemp = aSite" created a true copy of the original array.
Table of Contents