如何在vbscript中删除数组中的重复项?
代码:
dim XObj(100),xObjXml
for s=0 to xObjXml.length-1
XObj(s)=xObjXml(s).getAttribute("xsx")
next
请为此提出更好的答案。
答案 0 :(得分:3)
使用Dictionary收集数组的唯一项目:
>> a = Array(1, 2, 3, 1, 2, 3)
>> WScript.Echo Join(a)
>> Set d = CreateObject("Scripting.Dictionary")
>> For i = 0 To UBound(a)
>> d(a(i)) = d(a(i)) + 1
>> Next
>> WScript.Echo Join(d.Keys())
>>
1 2 3 1 2 3
1 2 3
>>
(顺便说一句:VBScript数组没有.length属性)
<强>加了:强>
字典的.Keys()方法返回(唯一)键的数组:
>> b = d.Keys()
>> WScript.Echo Join(b), "or:", b(2), b(1), b(0)
>>
1 2 3 or: 3 2 1
已添加II :(航空码!)
尝试获取XML集合中对象的唯一属性:
Dim xObjXml : Set xObjXml = ... get some collection of XML objects ...
Dim dicAttrs : Set dicAttrs = CreateObject("Scripting.Dictionary")
Dim i
For i = 0 To xObjXml.length - 1
Dim a : a = xObjXml(i).getAttribute("xsx")
dicAttrs(a) = dicAttrs(a) + 1
Next
Dim aAttrs : aAttrs = dicAttrs.Keys()
已添加III(抱歉!):
.Keys()是一个方法,因此应该这样调用:
Dim aAttrs : aAttrs = dicAttrs.Keys()
添加了IV:
有关工作样本,请参阅here。
答案 1 :(得分:0)
如果您不需要 Dictionary,您可以使用以下命令将数组中的每个元素与其自身进行比较。
Info = Array("Arup","John","Mike","John","Lisa","Arup")
x = 0
z = ubound(Info)
Do
x = x + 1
Do
z = z - 1
If x = z Then
Info(x) = Info(z)
ElseIf Info(x) = Info(z) Then
Info(x) = ""
End If
Loop Until z=0
z = ubound(Info)
Loop Until x = ubound(Info)
For each x in Info
If x <> "" Then
Unique = Unique & Chr(13) & x
End If
Next
MsgBox Unique