2010-12-08 116 views
0

动态获取VBScript(经典ASP)字典对象值时发生错误是的,它是一个漫长而复杂的标题......对不起。当For ... Each Loop

我正在用良好的时尚ASP在VBScript中工作。我有一个字典对象,字典中的每个对象都由它的Key和一个Array作为Item组成。

Dim myDictionary 
Set myDictionary = CreateObject("Scripting.Dictionary") 

myDictionary.Add "a", Array("a1","a2") 
myDictionary.Add "b", Array("b1","b2") 
myDictionary.Add "c", Array("c1","c2") 

我也传递到脚本字符串列表(并转换到一个数组),即与各种字典条目对应,因此,只有那些条目可以在网页上显示,并在顺序阵列。

Dim myText 
myText = "a, b, c" 

Dim myArray 
myArray = Split(myText,",") 

现在,我想遍历数组,并显示每个对应的键在myDictionary中的内容。

For Each thing in myArray 
    Response.Write myDictionary.Item(thing)(0) & "&nbsp;" & myDictionary.Item(thing)(1) & "<br />" & vbcrlf 
Next 

它在第一次迭代中完美工作,并正确地打印到页面。但在第二次迭代中,我得到一个错误。下面是页面上的全输出:

A1 + A2

Microsoft VBScript运行时错误

'800a000d' 类型不匹配:项目(...)“

/高山/ EN_US /testCase.asp,line 28

任何人都知道为什么这不起作用?自然地,这里显示的代码只是一个测试用例,但我的应用程序中存在完全相同的问题。

下面是完整的代码,所以你可以只需将其切成正贴到您的测试环境中,如果它可以帮助你帮助我这一个:

<%@LANGUAGE="VBSCRIPT"%> 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title>Iterating through Dictionary objects - Test Case</title> 
</head> 

<body> 

<% 


Dim myDictionary 
Set myDictionary = CreateObject("Scripting.Dictionary") 

myDictionary.Add "a", Array("a1","a2") 
myDictionary.Add "b", Array("b1","b2") 
myDictionary.Add "c", Array("c1","c2") 

Dim myText 
myText = "a, b, c" 

Dim myArray 
myArray = Split(myText,",") 

For Each thing in myArray 
    Response.Write myDictionary.Item(thing)(0) & "&nbsp;" & myDictionary.Item(thing)(1) & "<br />" & vbcrlf 
Next 

%> 


</body> 
</html> 

其他一些有趣的片段这个问题...

当我硬编码的迭代中所有三个字典条目,它工作正常:

For Each thing in myArray 
    Response.Write myDictionary.Item("a")(0) & "&nbsp;" & myDictionary.Item("a")(1) & "<br />" & vbcrlf 
    Response.Write myDictionary.Item("b")(0) & "&nbsp;" & myDictionary.Item("b")(1) & "<br />" & vbcrlf 
    Response.Write myDictionary.Item("c")(0) & "&nbsp;" & myDictionary.Item("c")(1) & "<br />" & vbcrlf 
Next 

产生以下:

A1 + A2
B1,B2,
C1 C2
A1 A2
B1,B2,
C1 C2
A1 + A2
B1,B2,
C1 C2

,并验证在for-each循环的 '东西' 变量工作:

For Each thing in myArray 
    Response.Write thing 
Next 

产生以下:

ABC

我很困惑...

谢谢大家!我非常感谢您提供的任何帮助。 :-)

干杯,
Lelando

回答

3

这是因为你有你的myText逗号后面的空格。 Split函数创建一个值为"a", " b", " c"的数组。后两个值不存在于您的字典中。

替换行

myText = "a, b, c" 

随着

myText = "a,b,c" 

或用", "改变你的标记符(注意空格)。

+0

嗯,那样做!由于我所有可能的关键术语都是单个单词,并且我知道将创建逗号分隔列表的人将使用空格*不一致*,我想也必须先从列表中删除所有空格。听起来很对你? – Lelando 2010-12-08 00:50:10