从数组中获取随机项

时间:2015-02-24 21:45:10

标签: arrays asp-classic

我从这个基本代码示例开始:

<%
block1 = "tree, ball, cheese, rabbit, waffle, planet, string, cat, dog, hole, hobbit, sing,"

wordArray1 = split(block1, ",")

For Each item In wordArray1
    Response.Write(item & "<br />")
Next

max=11
min = 1
Randomize
rand1 = Int((max-min+1)*Rnd+min)

response.write "<hr/>rand1: " & rand1 & "<hr/>"

w1 = wordArray1(0,rand1)

response.write "w1: " & w1 & "<hr/>"
%>

我首先用逗号分隔的单词列表(block1)。

我将其转换为数组(wordArray1)

我可以通过循环遍历并将数组值打印到页面来证明数组存在。

然后我希望能够从该数组中随机选择一个值。

我以为我可以这样做:

max=11
min = 1
Randomize
rand1 = Int((max-min+1)*Rnd+min)

response.write "<hr/>rand1: " & rand1 & "<hr/>"

w1 = wordArray1(0,rand1)

但是我收到了这个错误:

Microsoft VBScript runtime error '800a0009'
Subscript out of range: 'wordArray1'

如何随机访问其中一个阵列?

由于

1 个答案:

答案 0 :(得分:0)

您不是在创建多维数组,因此不应传入两个参数。改变这一行:

w1 = wordArray1(0,rand1)

到此:

w1 = wordArray1(rand1)