繁体   English   中英

检查经典asp数组中的变量是否

[英]Check if variable in classic asp array

我正在尝试检查变量的值是否在数组中。 有一些困难。 我的数组存储在 global.asa 中。

    Dim aTree(5)
   aTree(0) = "a"
    aTree(1) = "b"
    aTree(2) = "c"
    aTree(3) = "d"
    aTree(4) = "e"
    aTree(5) = "f"
       Application("aTree") = aTree 

我要检查的变量存储了一些 html 内容

<% If tree = "a" Then %>
     <div class="card bg_white">
            <h1 class="bold small-caps tbrown">my content</h1>
    </div>
<% End If %>

我正在尝试以这种方式进行检查

<% tree = Request("tree") 
if in_array(tree, aTree) then %>
You've found it
<% End if %>

我有这个可以工作的笨重版本

(tree <> "" and tree <> "a" and tree <> "b" and tree <> "c" and tree <> "d" and tree <> "e" and tree <> "f")

但我想要一种更优雅的方式来使用数组。

帮助不大。 谢谢。

没有内置的InArray()函数,但是应该足够简单以构建自己的函数。

Function InArray(theArray,theValue)
    dim i, fnd
    fnd = False
    For i = 0 to UBound(theArray)
        If theArray(i) = theValue Then
            fnd = True
            Exit For
        End If
    Next
    InArray = fnd
End Function

修改此函数以返回值的索引,而不只是返回true / false,这是读者的一项练习。 :)

这个解决方案更快(因为它不会潜在地循环遍历整个数组)并且优雅。 它使用滤波器 function:

https://www.w3schools.com/asp/func_filter.asp

function arrayIncludes(byval arr, byval value, byval matchCase)

    dim a, compareType

    arrayIncludes = false

    if (matchCase = false) then 
        compareType = 1
        value = lcase(value)
    else
        compareType = 0
    end if

    myFilter = Filter(arr, value, true, compareType)

    for a = 0 to ubound(myFilter)
        if (matchCase = false) then 
            myFilter(a) = lcase(myFilter(a))
        end if

        if (myFilter(a) = value) then 
            arrayIncludes = true
            exit for
        end if
    next

end function

用法(如果元素在数组中则返回 true,否则返回 false):

isIncluded = arrayIncludes(arrayToCheck, elementToSearch, true)  ' or false for matching case

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM