我在 .asp 文件中编写了以下 VB 脚本
Dim myArr(5, 6) '// a 6 * 7 array
For i = LBound(myArr, 1) to UBound(myArr, 1)
For j = LBound(myArr, 1) to UBound(myArr, 1)
myArr(i, j) = "i:" & i & ", j:" & j
next
next
Dim i
i = 0
For Each k In myArr
Response.Write("i:" & i ", k:" & k & "<br>")
i = i + 1
Next
使用 For Each 我可以迭代所有数组项, 问题是如何获取每个维度的索引?
例如:如何在第 10 次循环后获得 k 索引,即 2 和 4 ?
最佳答案
有用信息 1
首先考虑一下 VBS:
Option Explicit
Dim aaa(1,1,1)
Dim s : s = ""
Dim i, j, k
For i = LBound(aaa, 3) To UBound(aaa, 3)
For j = LBound(aaa, 2) To UBound(aaa, 2)
For k = LBound(aaa, 1) To UBound(aaa, 1)
aaa(k, j, i) = 4 * i + 2 * j + k
Next
Next
Next
Dim x
For Each x in aaa
s = s + CStr(x) + " : "
Next
MsgBox s
这将返回“0 : 1 : 2 : 3 : 4 : 5 : 6 : 7 :”,看起来不错,但请注意内部赋值中索引器的顺序aaa(k, j, i)
.如果我们使用更自然的aaa(i, j, k)
,我们会看到返回的订单是困惑的。那是因为我们假设最左边的索引器是最重要的,但它并不是最不重要的。
如果边界从 0 开始,那么对于第一个维度,索引 0..N 中的所有值都连续保存在其他维度为 0 的位置。然后,下一个维度为 1,下一组 0..N 成员第一个维度如下,依此类推。
有用信息 2
给定一个未知维数的数组,以下代码返回维数:
Function GetNumberOfDimensions(arr)
On Error Resume Next
Dim i
For i = 1 To 60000
LBound arr, i
If Err.Number <> 0 Then
GetNumberOfDimensions = i - 1
Exit For
End If
Next
End Function
解决方案
给定一个像这样的数组结构。
Dim arr(3,3,3)
Dim s : s = ""
Dim i, j, k
For i = LBound(arr, 3) To UBound(arr, 3)
For j = LBound(arr, 2) To UBound(arr, 2)
For k = LBound(arr, 1) To UBound(arr, 1)
arr(k, j, i) = 16 * i + 4 * j + k
Next
Next
Next
以下代码能够确定任意维度和大小的数组中每个项目的索引集。
Dim dimCount : dimCount = GetNumberOfDimensions(arr)
Redim dimSizes(dimCount - 1)
For i = 1 To dimCount
dimSizes(i - 1) = UBound(arr, i) - LBound(arr, i) + 1
Next
Dim index : index = 0
Dim item
For Each item in arr
s = "("
Dim indexValue, dimIndex
indexValue = index
For dimIndex = 0 To dimCount - 1
s = s + CStr((indexValue mod dimSizes(dimIndex)) - LBound(arr, dimIndex + 1)) + ", "
indexValue = indexValue \ dimSizes(dimIndex)
Next
Response.Write Left(s, Len(s) - 2) + ") = " + Cstr(item) + "<br />"
index = index + 1
Next
一个有趣的学术练习,不确定它有多大用处。
关于asp-classic - VB : how to get the index(es) of an array element if used in For Each,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10927917/