动态增加数组大小

VJV*_*VJV 5 asp-classic

我在ASP中有这个数组

CONST CARTPID = 0
CONST CARTPRICE = 1
CONST CARTPQUANTITY = 2
dim localCart(3,20)
Run Code Online (Sandbox Code Playgroud)

我像这样动态地向这个数组添加项目

localCart(CARTPID,i) = productId
localCart(CARTPRICE,i) = productPrice
localCart(CARTPQUANTITY,i) = 1
Run Code Online (Sandbox Code Playgroud)

问题是,在4个项目之后,我仍然可以添加项目,但UBound总是返回3.这导致我的条件失败.

我想在运行时增加此数组的大小,以便UBOUND可以返回最新值.

请让我知道我该怎么做.这是我的完整代码

'Define constants
 CONST CARTPID = 0
 CONST CARTPRICE = 1
 CONST CARTPQUANTITY = 2

 'Get the shopping cart.
 if not isArray(session("cart")) then
dim localCart(3,20)
 else
localCart = session("cart")
 end if

 'Get product information
 productID = trim(request.QueryString("productid"))
 productPrice = trim(request.QueryString("price"))

 'Add item to the cart

 if productID <> "" then
foundIt = false
for i = 0 to ubound(localCart)
    if localCart(CARTPID,i) = productId then
        localCart(CARTPQUANTITY,i) = localCart(CARTPQUANTITY,i)+1
        foundIt = true
        exit for
    end if
next
if not foundIt then
    for i = 0 to 20

        if localCart(CARTPID,i) = "" then
                            ***ReDim Preserve localCart(UBound(localCart, 1) + 1,20)***
            localCart(CARTPID,i) = productId
            localCart(CARTPRICE,i) = productPrice
            localCart(CARTPQUANTITY,i) = 1
            exit for
        end if
    next
end if
 end if
Run Code Online (Sandbox Code Playgroud)

Rob*_*ert 5

如果您在循环中动态添加项目,则需要使用该Redim Preserve()语句.您将需要使用该Preserve部件,这样您就不会丢失任何现有数据.

否则,如果您使用数组数据然后将其重新设置为另一组数据,则可以只使用该Redim()语句

以下是使用Redim()/ Redim Prevserve()Statments的一个很好的参考:http://classicasp.aspfaq.com/general/can-i-create-an-array-s-size-dynamically.html


Paw*_*iya 0

我认为每次添加新项目后用当前的 UBound+1 重新调整数组将使 UBound 最终为您提供最新值。

// New item addition code will go here
ReDim localCart(UBound(localCart, 1) + 1,20)
Run Code Online (Sandbox Code Playgroud)

因此,每次您添加新项目时,它都会使用新大小更新您的数组。