How do you add an item to an existing array in VBScript?
Is there a VBScript equivalent to the push function in Javascript?
i.e.
myArray has three items, "Apples", "Oranges", and "Bananas" and I want to add "Watermelons" to the end of the array.
ReDim Statement is used to declare dynamic-array variables and allocate or reallocate storage space. ReDim [Preserve] varname(subscripts) [, varname(subscripts)] Preserve − An Optional parameter used to preserve the data in an existing array when you change the size of the last dimension.
❮ Complete VBScript Reference. The Array function returns a variant containing an array. Note: The position of the first element in an array is zero.
The UBound function returns the largest subscript for the indicated dimension of an array. Tip: Use the UBound function with the LBound function to determine the size of an array.
The Filter function returns a zero-based array that contains a subset of a string array based on filter criteria. Note: If no matches of the value parameter are found, the Filter function will return an empty array.
Arrays are not very dynamic in VBScript. You'll have to use the ReDim Preserve statement to grow the existing array so it can accommodate an extra item:
ReDim Preserve yourArray(UBound(yourArray) + 1) yourArray(UBound(yourArray)) = "Watermelons"
For your copy and paste ease
' add item to array Function AddItem(arr, val) ReDim Preserve arr(UBound(arr) + 1) arr(UBound(arr)) = val AddItem = arr End Function
Used like so
a = Array() a = AddItem(a, 5) a = AddItem(a, "foo")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With