使用 dims 作为数组长度

Using dims as array lengths

基本上,我正在编写一个 .asp 文件来创建一个由数组中的字符串组成的 HTML table。

我需要数组是动态的,这样我就可以从文本文件向数组添加任意数量的字符串。我遇到的是创建动态数组的问题。

到目前为止我尝试过的是:

set fs=Server.CreateObject("Scripting.FileSystemObject")
set f=fs.OpenTextFile("c:\inetasp\test.txt",1)
dim row 

do Until f.AtEndOfStream = true
    f.Skipline
loop

row=CInt(f.Line) 'my try of making "row" an integer and preventing the error...'
dim results()
results=(row-1) 'The line consisting the error which has something to do with "row"'
f.Close

for i=0 to row-1
    results(i)=f.ReadLine
    Response.Write("Results" & result(i))
next

如您所见,我正在尝试使用 dim 来设置数组的长度。

我是经典 asp 的新手,所以我真的需要一些帮助。 如果需要,我很乐意添加任何规范:)

正如 Dijkgraaf 在评论中所说,您正在寻找的语法是

ReDim results(row-1)

但是,如果您所做的只是边读边写行,为什么需要将它们放在数组中?

Set fs = Server.CreateObject("Scripting.FileSystemObject")
Set f = fs.OpenTextFile("c:\inetasp\test.txt",1)
Dim r, i
i = 0
Do Until f.AtEndofStream
    i = i + 1
    r = f.ReadLine
    Response.Write "<p>Result " & i & ": " & r & "</p>"
Loop
f.Close
Set f = Nothing
Set fs = Nothing

如果您绝对确实需要数组中的结果,快速而肮脏的方法是在第一次循环获取文件大小后再次打开文件:

Set fs = Server.CreateObject("Scripting.FileSystemObject")
Set f = fs.OpenTextFile("c:\inetasp\test.txt",1)
Dim r, i
i = -1
Do Until f.AtEndofStream
    i = i + 1
    f.Skipline
Loop
f.Close
If i >= 0 Then Redim r(i)
Set f = fs.OpenTextFile("c:\inetasp\test.txt",1)
i = -1
Do Until f.AtEndOfStream
    i = i + 1
    r(i) = f.ReadLine
Loop
f.Close
Set f = Nothing
Set fs = Nothing

但这意味着您要循环遍历文本文件两次。如果它是一个大文本文件,那可能会有很多开销。您可以改为对文本文件的大小做出最好的猜测,然后根据需要执行 Redim Preserve

Set fs=Server.CreateObject("Scripting.FileSystemObject")
Set f=fs.OpenTextFile("c:\inetasp\test.txt",1)
Dim r(), i
Redim r(500) '- use your best guess at the number of lines
i = -1
Do Until f.AtEndofStream
    i = i + 1
    If i > UBound(r) Then
        '- redim has its own overhead, so minimize # of times it's called
        Redim Preserve r(i+50) 
    End If
    r(i) = f.ReadLine
Loop
f.Close
Set f = Nothing
Set fs = Nothing