所以我试图从动态会话数组中删除一个特定的元素。我当前的数组删除了错误的元素,并留下了我希望摆脱的元素
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”项目,而是删除随机项目。
答案 0 :(得分:4)
示例代码中的逻辑执行以下操作:
用sku替换倒数第二个项目。
sessionArray(length-1)=sku
删除最后一项。
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 :(得分:1)
如果要使用值排除项目,则应使用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