使用dims作为数组长度

时间:2015-11-19 22:53:13

标签: arrays asp-classic

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

我需要数组是动态的,所以我可以从文本文件中向数组添加任意数量的字符串。我所拥有的是创建动态数组的问题。

到目前为止,我所尝试的是:

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

如您所见,我尝试使用昏暗来设置数组的长度。

我是经典asp的新手,所以我真的可以使用一些帮助。 如果被要求,我很乐意添加任何规格:)

1 个答案:

答案 0 :(得分:2)

正如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

如果你绝对需要数组中的结果,那么快速&amp;脏的方法是在第一次循环后再次打开文件以获得它的大小:

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