Increase array size dynamically

I have this array in ASP

CONST CARTPID = 0
CONST CARTPRICE = 1
CONST CARTPQUANTITY = 2
dim localCart(3,20)

I add elements to this array dynamically, like this

localCart(CARTPID,i) = productId
localCart(CARTPRICE,i) = productPrice
localCart(CARTPQUANTITY,i) = 1

The problem is that after 4 elements I can still add elements, but UBound always returns 3. Because of what, my conditions do not work.

I want to increase the size of this array at runtime so that UBOUND can return the last value.

Please let me know how I can do this. Here is my full code

'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
+5
source share
3 answers

I think reassigning an array with current UBound + 1 after each addition of a new element will cause UBound to give you the last value.

// New item addition code will go here
ReDim localCart(UBound(localCart, 1) + 1,20)

Therefore, it will update your array with a new size every time you add a new element.

0

, Redim Preserve(). Preserve, .

, , Redim()

Redim()/Redim Prevserve() : http://classicasp.aspfaq.com/general/can-i-create-an-array-s-size-dynamically.html

+5

The first dimension has only 3 lengths, and the second is 20. If you want the UBound of the second dimension, do the following:

UBound(localCart, 2)

Which returns 20. You can combine this with ReDim Preserve.

+1
source

All Articles