VBScript Scripting Techniques > Data > ArrayLists
Arrays can be used in any version of VBScript, and in any Windows version, provided that Windows Script Host is installed.
A (minor) disadvantage of VBScript arrays is that, in order to add an element to an existing array, and then sort that array, you need to:
'  Retrieve the index number of the last element in the array idxLast = UBound( myArray ) '  Resize the array, preserving the current content ReDim Preserve myArray( idxLast + 1 ) '  Add the new element to the array myArray( idxLast + 1 ) = strNewValue '  Sort the array using a "bubble sort" algorithm borrowed from the Scripting Guys For i = ( UBound( myArray ) - 1 ) to 0 Step -1 For j= 0 to i If UCase( myArray( j ) ) > UCase( myArray( j + 1 ) ) Then strHolder = myArray( j + 1 ) myArray( j + 1 ) = myArray( j ) myArray( j ) = strHolder End If Next Next
In this article by the Scripting Guys an alternative technique is discussed: ArrayLists.
The ArrayList is a .NET Framework class, which means it requires the .NET Framework.
The following code is used to create an ArrayList and "populate" it with some data:
' this code creates and populates an ArrayList Set myArrayList = CreateObject( "System.Collections.ArrayList" ) myArrayList.Add "F" myArrayList.Add "B" myArrayList.Add "D" myArrayList.Add "C"
Now, to add an element and sort the ArrayList, all we need to do is:
'  add the new element to the ArrayList myArrayList.Add "Z" '  sort the ArrayList myArrayList.Sort
And how about deleting an element?
In an array you would need to "shift" the elements to fill the gap and then ReDim the array again.
In an ArrayList you would use either
myArrayList.Remove "element_value" or
To learn more about the possibilities of the ArrayList class, read this Scripting Guys' article, browse the MSDN Library, and download and try my own ArrayLst.vbs demo script.
page last uploaded: 2018-12-20, 10:50