函數簽名
Function array_no(cxstr1, cxstr2, cxstr3)
' cxstr1: 來源字串
' cxstr2: 分隔字元
' cxstr3: 選擇性索引(0 回傳整串,>0 回傳指定項目)
完整程式碼
Function array_no(cxstr1, cxstr2, cxstr3)
If Len(cxstr3) > 0 Then
If Not IsNumeric(cxstr3) Then
array_no = "參數3必須為數字"
Exit Function
End If
Else
array_no = "參數3必須為數字"
Exit Function
End If
If IsArray(cxstr1) Then
array_no = "參數1不能為陣列"
Exit Function
End If
If cxstr1 = "" Or IsEmpty(cxstr1) Then
array_no = "無資料"
Exit Function
End If
Dim ss, cxs, sss, m, cc
ss = Split(cxstr1, cxstr2)
cxs = cxstr2 & ss(0) & cxstr2
sss = cxs
For m = 0 To UBound(ss)
cc = cxstr2 & ss(m) & cxstr2
If InStr(sss, cc) = 0 Then
sss = sss & ss(m) & cxstr2
End If
Next
array_no = Right(sss, Len(sss) - Len(cxstr2))
array_no = Left(array_no, Len(array_no) - Len(cxstr2))
If cxstr3 <> 0 Then
Dim cx_sp
cx_sp = Split(array_no, cxstr2)
If cxstr3 > UBound(cx_sp) Then
array_no = cx_sp(UBound(cx_sp))
Else
array_no = cx_sp(cxstr3)
End If
End If
End Function
使用範例
<%
Dim src : src = "a,b,c,a,d,b,e"
Dim result : result = array_no(src, ",", 0)
Response.Write result ' 輸出: a,b,c,d,e
%>
改進建議
- 原函數以字串模擬集合,效能較差;大量資料建議使用
Scripting.Dictionary 去重。
- 參數檢查邏輯可簡化,
cxstr3 應為 Optional 參數。
- 回傳型別不一致(字串/錯誤訊息/單一項目),建議統一回傳陣列或 Dictionary。
Dictionary 版去重範例
Function UniqueArray(arr, delimiter)
Dim dict, item, key
Set dict = CreateObject("Scripting.Dictionary")
For Each item In arr
dict(item) = True
Next
Dim res() : ReDim res(dict.Count - 1)
Dim i : i = 0
For Each key In dict.Keys
res(i) = key: i = i + 1
Next
If delimiter <> "" Then
UniqueArray = Join(res, delimiter)
Else
UniqueArray = res
End If
End Function