我有一个购物车,使用2d数组Cart(3, 20)
来存储会话中的用户商店
它存储如下数据:
Cart(0,0) = Product_ID
Cart(1,0) = Product_Name
Cart(2,0) = Product_Price
Cart(3,0) = Product_Qty
我想基于product_id计算项目(我们没有重复的product_id) 我在这里找到了一个功能:
Function UniqueEntryCount(SourceRange)
Dim MyDataset
Dim dic
Set dic=Server.CreateObject("Scripting.Dictionary")
MyDataset = SourceRange
For i = 1 To UBound(MyDataset, 2)
if not dic.Exists(MyDataset(0, i)) then dic.Add MyDataset(0, i), ""
Next
UniqueEntryCount = dic.Count
Set dic = Nothing
End Function
但仍有一个问题,当我的购物车为空时,它会显示1
怎么解决它?
答案 0 :(得分:0)
一个统一的固定数组(Dim a(i,j))包含i * j个空元素;你的
if not dic.Exists(MyDataset(0, i)) then dic.Add MyDataset(0, i), ""
将拿起并计算第一个空项目。在代码中展示:
Dim afCart(3, 4)
Dim dicPID : Set dicPID = countPID00(afCart)
Dim aKeys : aKeys = dicPID.Keys
Dim vKey : vKey = aKeys(0)
WScript.Echo "A", dicPID.Count, TypeName(vKey)
Set dicPID = countPID(afCart)
WScript.Echo "B", dicPID.Count
afCart(0, 0) = "ignored"
afCart(0, 1) = 4711
afCart(0, 2) = 4712
afCart(0, 3) = 4711
' afCart(0, 4) = "not initialized/Empty"
Set dicPID = countPID(afCart)
WScript.Echo "C"
For Each vKey In dicPID.Keys
WScript.Echo "", vKey, "=", dicPID(vKey)
Next
Function countPID00(afCart)
Dim dicRVal : Set dicRVal = CreateObject("Scripting.Dictionary")
Dim MyDataset : MyDataset = afCart ' waste of ressources
Dim iRow
For iRow = 1 To UBound(MyDataset, 2)
If Not dicRVal.Exists(MyDataset(0, iRow)) Then
dicRVal(MyDataset(0, iRow)) = "" ' loss of info; will pick up Empty item
End If
Next
Set countPID00 = dicRVal
End Function ' countPID00
Function countPID(afCart)
Dim dicRVal : Set dicRVal = CreateObject("Scripting.Dictionary")
Dim iRow
For iRow = 1 To UBound(afCart, 2)
If Not IsEmpty(afCart(0, iRow)) Then
dicRVal(afCart(0, iRow)) = dicRVal(afCart(0, iRow)) + 1
End If
Next
Set countPID = dicRVal
End Function ' countPID
输出:
A 1 Empty
B 0
C
4711 = 2
4712 = 1