Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add item to array in VBScript

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.

like image 643
Choy Avatar asked Jan 05 '11 14:01

Choy


People also ask

What is ReDim in VBScript?

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.

What is an array in VBScript?

❮ Complete VBScript Reference. The Array function returns a variant containing an array. Note: The position of the first element in an array is zero.

What is UBound in VBScript?

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.

How will you get a subset of an array in VBScript?

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.


2 Answers

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" 
like image 74
Frédéric Hamidi Avatar answered Oct 08 '22 09:10

Frédéric Hamidi


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") 
like image 29
Charles Clayton Avatar answered Oct 08 '22 08:10

Charles Clayton