简体   繁体   English

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

[英]Check if variable in classic asp array

I'm trying to check if the value of a variable is in an array.我正在尝试检查变量的值是否在数组中。 Having some difficulty.有一些困难。 My array is stored it the global.asa.我的数组存储在 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 

The variable I'm trying to check stores some html content我要检查的变量存储了一些 html 内容

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

I'm trying to do the check this way我正在尝试以这种方式进行检查

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

I've got this clunky version that works我有这个可以工作的笨重版本

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

But I'd like a more elegant way of doing it with an array.但我想要一种更优雅的方式来使用数组。

Little help.帮助不大。 Thanks.谢谢。

There's no built-in InArray() function, but it should be simple enough to build your own. 没有内置的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

Modifying this function to return the index of the value instead of just true/false is left as an exercise for the reader. 修改此函数以返回值的索引,而不只是返回true / false,这是读者的一项练习。 :) :)

This solution is much faster (as it doesn't potentially loop through the whole array) and elegant.这个解决方案更快(因为它不会潜在地循环遍历整个数组)并且优雅。 It uses the Filter function:它使用滤波器 function:

https://www.w3schools.com/asp/func_filter.asp 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

Usage (returns true if element is in array, or false if it is not):用法(如果元素在数组中则返回 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