Saturday 18 May 2013

How we can define array in vb script

Arrays are used to store multiple values in the same variable.

We can define array in vb script in 4 different ways.
  • dim a(10)  - static array of 11 elements
  • dim b()   - dynamic array
  • a = array(1,2,3,4) - declare array with values
  • a = split("as*dfdf*sdsd","*") - array is automatically created with a(0) = as, a(1)=dfdf , a(2)=sdsd
Various Operations that can be performed on the array are mentioned below
  1. Iterate through all elements in the array
  2. Find the lower bound and upper bound of the array
  3. Filter the array
  4. Join the elements in the array
  5. Sort the elements in the array
1. Iterate through all elements in the array
Below example will illustrate how we can access all elements in the array.


a = array(34,5,66,"sagar", 44.4)

for i=0 to ubound(a)
    
    'Print each element in the array one by one.   
    msgbox a(i)
   
next

2.Find the upper bound and lower bound in the array
Below example will illustrate how we can find the upper bound and lower bound of the array.

a = array(34,5,66,"sagar", 44.4)
Msgbox ubound(a) 'print 4
Msgbox lbound(a) 'prints 0

3.Filter the array
We can use filter function to filter elements in the array.

Syntax of the Filter method is given below.
'Filter(arrayToSearch,substringToSearch[,include [,compare]])

  1. arrayToSearch - This is the array whose elements will be searched
  2. substringToSearch - String to search in array
  3. include - this can be true/false. If true, it will return all matching values If false, it will return all non-matching values. Default is true.
  4. compare - this flag can be 0 or 1. If 0 means it will be binary comparison. else it will be textual comparison. Default is binary comparison -0


Below example will illustrate how we can filter the elements in array.

'***********************************************************
a = array("amol","sachin","arjun","Sagar")
b = filter(a,"s",true,0)
' b = filter(a,"s")    .....both are same ...binary comparison....case sensitive

for i=0 to ubound(b)
 msgbox b(i)  'will print sachin
next
'***********************************************************
a = array("amol","sachin","arjun","Sagar")
b = filter(a,"s",true,1)

for i=0 to ubound(b)
 msgbox b(i)          'will print sachin and Sagar........textual comparison....case insensitive
next
'***********************************************************
a = array("amol","sachin","arjun","Sagar")
b = filter(a,"s",false,1)

for i=0 to ubound(b)
 msgbox b(i)   'will print amol and arjun ........non-matching elements.
next

4. Join the elements in the array

Join function is used to join the elements in the array.

a = array("sachin", "plays", "cricket")
msgbox join(a)  'will print sachin plays cricket

a = array("sachin", "plays", "cricket")
msgbox join(a,"*")  'will print sachin*plays*cricket



No comments:

Post a Comment

Total Pageviews