如何在vbscript中检查数组中的变量

时间:2017-02-13 15:12:20

标签: arrays vbscript asp-classic

我正在重构我的代码并试图减少重复。我有这个工作代码

<% If tree <> "" or (info <> "" and info <> "links" and info <> "privacy" and info <> "talks") Then %>
            write stuff
<% End If %>

我将信息变量放入数组

Dim info(3)
info(0) = "Talks"
info(1) = "Privacy"
info(2) = "Links"

我不清楚迭代数组

<% If tree <> "" or (info <> "" and **info <> arrayInfo** Then %>
            write stuff
<% End If %>

帮助不大。感谢。

5 个答案:

答案 0 :(得分:6)

如果您想使用一个表达式(.Exists)来获取有关集合的所有元素的事实(包含与否),则需要字典。看看:

Option Explicit

Dim aInfo(2)  ' last index; not size
aInfo(0) = "Talks"
aInfo(1) = "Privacy"
aInfo(2) = "Links"
Dim dicInfo : Set dicInfo = CreateObject("Scripting.Dictionary")
dicInfo.CompareMode = vbTextCompare
Dim i
For Each i In aInfo
    dicInfo(i) = 0
Next
For Each i In Split("Talks Other Links Else")
    If dicInfo.Exists(i) Then
       WScript.Echo i, "found"
    Else
       WScript.Echo "no", i, "in", Join(dicInfo.Keys())
    End If
Next

输出:

cscript 42207316.vbs
Talks found
no Other in Talks Privacy Links
Links found
no Else in Talks Privacy Links

答案 1 :(得分:2)

另一种技术是创建一个字符串和instr()。

InStr函数([开始,]字符串1,字符串[,比较]) 如果在string1中找不到string2,则InStr返回0.

请注意,管道分隔符在我们搜索的字符串的第一个和最后一个位置以及我们要匹配的内容中都很重要。否则你会得到假阳性。

<%
dim sText 
sText="|Talks|Privacy|Links|"

  If tree <> "" or (len(info) > 0 and instr(1, sText, "|" info & "|") ) Then %>
            write stuff
<% End If %>

这项技术值得用一些字符串进行测试。默认比较模式区分大小写,但您可以使其不敏感。

有关详细信息,请参阅http://www.w3schools.com/asp/func_instr.asp

它不像使用字典那样纯粹,但值得注意。

答案 2 :(得分:2)

虽然我同意使用Instr功能的上述答案,但还有另一种选择。您的问题是询问如何遍历数组以测试值。使用For..Next循环。代码示例如下。

dim arrInfo(2)
dim blnInfoGood

blnInfoGood = true

arrInfo(0) = "Talks"
arrInfo(1) = "Privacy"
arrInfo(2) = "Links"

for k = lbound(arrInfo) to ubound(arrInfo)
    if info = arrInfo(k) then
        blnInfoGood = false
        exit for
    end if
next

if tree <> "" or blnInfoGood then
    ' Write stuff
end if

希望这有帮助。

答案 3 :(得分:2)

使用字典并使用更简单的条件。

<%
set obj = server.createObject("scripting.dictionary")

obj.add "links", "links"
obj.add "privacy", "privacy"
obj.add "talks", "talks"

if tree <> "" and obj.exists(info)=false then
     'write stuff
end if

set obj = nothing
%>

答案 4 :(得分:0)

这是迭代数组的最简单方法,因为你具体询问了这个。

    Dim info(3)
    info(0) = "Talks"
    info(1) = "Privacy"
    info(2) = "Links"

    for i = 0 to 2
        if tree = info(i) then
            'do stuff here with match
        end if
    next
相关问题