0


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 计算 Items (我们没有重复的 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

怎么能解决呢?

4

1 回答 1

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
于 2012-08-09T06:47:03.283 回答