这是代码:
'creates the msxml object
Set xmlDoc = CreateObject("Msxml2.DOMDocument.6.0")
Dim retVal
'load the xml data of the script
retVal=xmlDoc.load(argFilePath)
Dim fso, folder, sFolder
Dim xmlDataPath, curNode
'get input folder
Set curNode=xmlDoc.selectSingleNode("//ScriptXmlData/inputFilePath")
Dim inputFolder, outputFolder, hotLoc
inputFolder=CSTR(curNode.text)
'location of jdf files
sFolder=inputFolder
'creating file getting object
Set fso = CreateObject("Scripting.FileSystemObject")
Set folder = fso.GetFolder(sFolder)
Dim amount, fName, arrC, i
i=0
'loop for getting amounts
For each folderIdx In folder.files
If fso.GetExtensionName(folderIdx.Name) = "jdf" Then
'increase array size
Redim arrC(i)
'get folder name
fName=folderIdx.Name
'get file path
xmlDataPath = sFolder+"\"+fName
'load the xml data of the script
retVal = jdfDoc.load(xmlDataPath)
'get amount
Set curNode = jdfDoc.selectSingleNode("//jdf:JDF/jdf:ResourceLinkPool/jdf:ComponentLink")
amount = curNode.getAttribute("Amount")
'Create array that holds amount
arrC(i)=amount
i=i+1
End If
Next
wscript.echo arrC(0)
wscript.echo arrC(1)
wscript.echo arrC(2)
我们的问题是,一旦arrC退出循环,它的一些值就会丢失。 例如,在循环内部我们的数组是:
ARRC(0)= 100
ARRC(1)= 150
ARRC(2)= 200
一旦离开循环,就像代码末尾的测试一样,它的值是;
ARRC(0)= “”
ARRC(1)= “”
ARRC(2)= 200
有人可以解释一下吗?
谢谢!
答案 0 :(得分:2)
ReDim
的情况下使用时, Preserve
不会保留数组的元素。改变行
Redim arrC(i)
到
Redim Preserve arrC(i)
您不需要索引变量BTW。将arrC
初始化为循环外的空数组时,可以使用上限作为索引:
ReDim arrC(-1)
For Each folderIdx In folder.files
If fso.GetExtensionName(folderIdx.Name) = "jdf" Then
...
ReDim Preserve arrC(UBound(arrC)+1)
arrC(UBound(arrC)) = amount
End If
Next
但是,由于ReDim Preserve
实际上创建了一个 new 数组并从旧数组中复制现有元素,因此随着数组大小的增加,它必然会表现不佳。您可能希望使用array list代替:
Set arrC = CreateObject("System.Collections.ArrayList")
For Each folderIdx In folder.files
If fso.GetExtensionName(folderIdx.Name) = "jdf" Then
...
arrC.Add amount
End If
Next