数组索引
- 来源: https://www.freebasic.net/wiki/wikka.php?wakka=ProPgArrayIndex
- 最后更新: 2019-10-03
描述
以下示例说明数组元素的使用。
如果我们有一个元素为 1 到 10 的数组 myArray,其中填充了随机数据:
索引 数据
1 5
2 2
3 6
4 5
5 9
6 1
7 0
8 4
9 5
10 7可以通过指向数组元素的索引来单独访问每条数据:
start GeSHi
vb
Print myArray(5)end GeSHi
打印 myArray 第五个元素中包含的数据,输出结果为:
9要更改数组的内容,像使用其他变量一样使用它:
start GeSHi
myArray(3) = 0end GeSHi
要打印 myArray(3) 的内容,使用以下命令:
start GeSHi
vb
Print myArray(3)end GeSHi
输出结果为:
0可以使用另一个变量对数组元素进行索引。在此示例中,我们将数组中的所有元素设置为零:
start GeSHi
vb
Dim a As Integer
For a = 1 To 10
myArray(a) = 0
Next aend GeSHi
要将随机数组元素更改为随机值:
start GeSHi
vb
Dim Index As Integer
Dim Value As Integer
index = Int(Rnd(1) * 10) + 1 'This line will simply return a random value between 1 and 10
Value = Int(Rnd(1) * 10) + 1 'This line will do the same
myArray(index) = Valueend GeSHi
示例
start GeSHi
vb
Declare Sub PrintArray()
Dim Numbers(1 To 10) As Integer
Dim Shared OtherNumbers(1 To 10) As Integer
Dim a As Integer
Numbers(1) = 1
Numbers(2) = 2
OtherNumbers(1) = 3
OtherNumbers(2) = 4
PrintArray ()
For a = 1 To 10
Print Numbers(a)
Next a
Print OtherNumbers(1)
Print OtherNumbers(2)
Print OtherNumbers(3)
Print OtherNumbers(4)
Print OtherNumbers(5)
Print OtherNumbers(6)
Print OtherNumbers(7)
Print OtherNumbers(8)
Print OtherNumbers(9)
Print OtherNumbers(10)
Sub PrintArray ()
Dim a As Integer
For a = 1 To 10
Print otherNumbers(a)
Next a
End Subend GeSHi
参见
返回 目录