我有一个数组,它包含多次出现的值。例如:
dim myArray
Wscript.StdOut.WriteLine "Enter a word: "
word1 = Wscript.StdIn.ReadLine
Wscript.StdOut.WriteLine "Enter a word: "
word2 = Wscript.StdIn.ReadLine
Wscript.StdOut.WriteLine "Enter a word: "
word3 = Wscript.StdIn.ReadLine
Wscript.StdOut.WriteLine "Enter a word: "
word4 = Wscript.StdIn.ReadLine
Wscript.StdOut.WriteLine "Enter a word: "
word5 = Wscript.StdIn.ReadLine
这些输入将被放入一个数组中:
myArray = Array(word1, word2, word3, word4, word5)
现在如果最终用户输入了(" steve"," steve"," doug"," doug",&#34 ;史蒂夫&#34)
如果我这样做:
for i = 1 to UBound(myArray)
Wscript.StdOut.WriteLine myArray(i) & ", "
next
我的明显结果将是
"steve",
"steve",
"doug",
"doug",
"steve",
如果我希望结果只是
,该怎么办?steve,
doug,
关于我可以做什么来迭代这个数组并且只显示在数组中出现多次的值的任何建议。 感谢。
答案 0 :(得分:1)
使用Scripting.Dictionary对象。使用.Exists
检查新添加内容,或使用速记覆盖重复项的项目。
<强> dict_test.vbs 强>
Dim dWORDs : Set dWORDs = CreateObject ("Scripting.Dictionary")
dWORDs.CompareMode = 1
Dim prmpt : prmpt = "Enter a word: "
Wscript.StdOut.WriteLine prmpt
dWORDs.Item(Wscript.StdIn.ReadLine) = Wscript.StdIn.ReadLine
Wscript.StdOut.WriteLine prmpt
dWORDs.Item(Wscript.StdIn.ReadLine) = Wscript.StdIn.ReadLine
Wscript.StdOut.WriteLine prmpt
dWORDs.Item(Wscript.StdIn.ReadLine) = Wscript.StdIn.ReadLine
Wscript.StdOut.WriteLine prmpt
dWORDs.Item(Wscript.StdIn.ReadLine) = Wscript.StdIn.ReadLine
Wscript.StdOut.WriteLine prmpt
dWORDs.Item(Wscript.StdIn.ReadLine) = Wscript.StdIn.ReadLine
Dim wrd
For Each wrd In dWORDs
Wscript.StdOut.WriteLine "key: " & wrd & " item: " & dWORDs.Item(wrd)
Next
dWORDs.RemoveAll: Set dWORDs = Nothing
它演示了“简写”方法,即添加新的或覆盖现有字典键而不会出错。剩下的是可以使用For .. Each语句枚举的唯一键列表。
答案 1 :(得分:1)
为循环中的每个元素询问一次,使用Join(),并且没有绒毛:
Option Explicit
Dim dWORDs : Set dWORDs = CreateObject ("Scripting.Dictionary")
dWORDs.CompareMode = vbTextCompare
Dim prmpt : prmpt = "Enter a word: "
Dim wrd
Do
Wscript.StdOut.WriteLine prmpt
wrd = Trim(Wscript.StdIn.ReadLine())
If "" = wrd Then Exit Do
dWORDs.Item(wrd) = 0
Loop
WScript.Echo Join(dWORDs.Keys(), ",")