VBS数组函数学习实例分析

2019-01-15 22:29:11于海丽

例三:使用循环来比较数组里是否包含某值

Dim arr, i, str

arr = array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "f", "g")
str = "a"
For i = 0 To UBound(arr)
 If arr(i) = str Then
  Exit For
 end if
Next
If i <= UBound(arr) Then
 msgbox "arr中包含str的值!"
 Else
 msgbox "arr中不包含str的值!"
End If

例四:使用函数组合来比较数组里是否包含某值(优化逻辑)

Dim arr, i, str

arr = array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "f", "g")
str = "a"
If InStr(Join(arr, "|"), str) > 0 Then
 msgbox "arr中包含str的值!"
 Else
 msgbox "arr中不包含str的值!"
End If

灵活应用各种函数命令,可以节约大量的多余代码,不仅精简代码结构,提供执行效率。

例五:VBS中数组作为函数的返回值

Function GenerateRandom()

 Dim myarray(2)
 Dim aa, bb, cc
 Dim myvalue, bbbase, ccbase 
 bbbase=array("Beijing", "NewYork", "Copenhagen", "Paris", "London", "Gothenborg")
 ccbase=array("China", "America", "Denmark", "Franch", "England", "Sweden")
 'Get a number contains 8 characters
 aa= Int((99999999 - 11111111+ 1) * Rnd + 11111111)
 ' Get a number between 1 to 6
 myvalue=Int((6 * Rnd) + 1)
 bb=bbbase(myvalue)
 cc=ccbase(myvalue)
 myarray(0)=CStr(aa)
 myarray(1)=bb
 myarray(2)=cc 
 GenerateRandom=myarray 
 End Function
'****************************************************
' Call the function 
Dim testarr 
testarr=GenerateRandom
msgbox testarr(0)
msgbox testarr(1) 
msgbox testarr(2)

例六:数组排序

Function fSortArray(aSortThisArray)

 Dim oArrayList, iElement
 Set oArrayList = CreateObject( "System.Collections.ArrayList" )
 For iElement = 0 To UBound(aSortThisArray)
  oArrayList.Add aSortThisArray(iElement)
 Next
 oArrayList.Sort
 set fSortArray = oArrayList
End Function
 
myarray=Array(50,20,30)
MsgBox myarray(0)
MsgBox fSortArray(myarray)(0)
 
'CreateObject( "System.Collections.ArrayList" )调用了mscoree.dll,是.NET Framework相关组件。