【问题标题】:Dynamic session array remove specific element动态会话数组删除特定元素
【发布时间】:2015-01-13 12:18:54
【问题描述】:

所以我试图从我的动态会话数组中删除一个特定元素。我当前的数组删除了错误的元素并留下了我希望摆脱的元素

sku = "the_item_value"
sessionArray = session("cart")
Dim length : length = Ubound(sessionArray)
sessionArray(length-1)=sku
ReDim Preserve sessionArray(length-1)
session("cart") = sessionArray

所以这是我当前的代码,它从我的会话数组中删除了一个项目。但是,它不会删除“sku”项目,它会删除随机项目。

【问题讨论】:

    标签: arrays session asp-classic vbscript


    【解决方案1】:

    您的示例代码中的逻辑执行以下操作:

    1. 用 sku 替换倒数第二个项目。

      sessionArray(length-1)=sku

    2. 删除最后一项。

      ReDim Preserve sessionArray(length-1)

    这显然不是你想要的。相反,您需要逻辑来查找 sku 项目,然后将其删除。

    如果项目的顺序无关紧要,您可以这样做:

    Sub RemoveArrayItem(array, item)
        ' Find item
        For i = LBound(array) To UBound(array)-1
            If array(i) = item Then
                ' Replace the item with last item
                array(i) = array(UBound(array))
                Exit For
            End If
        Next
    
        ' Remove the last item which is either a duplicate or it is the item
        ' (assuming that the item is definitely in the array)
        ReDim Preserve array(UBound(array)-1)
    End Sub
    
    sku = "the_item_value"
    sessionArray = session("cart")
    
    RemoveArrayItem sessionArray, sku
    
    session("cart") = sessionArray
    

    【讨论】:

    • +1 但假设 LBound = 1 这不一定是真的,如果数组的 LBound 不为 1,则替换为 LBound(sessionArray) 也可能会产生误导。因为 UBound 便宜且 @ 987654326@ 只使用了两次我会完全删除该变量。最后考虑重组为Sub 以创建通用的可重用“RemoveArrayItem”操作。
    • @AnthonyWJones 不错。我的 VBScript 有点生疏了。更新了答案以包含您的修复/建议。谢谢!
    【解决方案2】:

    如果要使用值排除项目,则应使用 Filter 函数。 看看:

    Dim myArray, sku, myFilteredArray
    sku = "the_item_value"
    myArray = Array("other", "other", "other", sku)
    Response.Write "Original:<br />" & Join(myArray, "<br />") 'check original
    myFilteredArray = Filter(myArray, sku, False, vbBinaryCompare)
    Response.Write "<hr />"
    Response.Write "Excluded:<br />" & Join(myFilteredArray, "<br />") 'check filtered
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-11-01
      • 1970-01-01
      • 2019-06-03
      • 2016-11-11
      • 1970-01-01
      相关资源
      最近更新 更多