Thứ Năm, 3 tháng 5, 2012

Can I create an array's size dynamically?


VBScript's arrays have quite a few limitations. You may have noticed if you try this:

<%
    x = 15
    Dim demoArray(x)
%>

You get this error:

Microsoft VBScript compilation (0x800A0402)
Expected integer constant

To work around this, you need to declare the array without a size (or with a constant size, e.g. 0), and then re-dimension it from the variable. Here are two examples; one using a simple array, the other a multi-dimensional array:

<%
    x = 15
    Dim demoArray()
    ReDim demoArray(x)
%>

<%
    x = 15
    y = 10
    Dim demoArray()
    ReDim demoArray(x,y)
%>

Note that if you want to increase the size of an array within a loop, and want to preserve the existing values assigned to the array, you need to use the Preserve keyword (otherwise, the array gets erased and re-created, thus destroying all your values):

<%
    Dim demoArray()
    for i = 1 to 5
        ReDim Preserve demoArray(i)
        DemoArray(i) = "test" & i
    next
%>
(http://classicasp.aspfaq.com/general/can-i-create-an-array-s-size-dynamically.html)

Không có nhận xét nào:

Đăng nhận xét