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.
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
<% 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.
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. :)
This solution is much faster (as it doesn't potentially loop through the whole array) and elegant. It uses the Filter 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
Usage (returns true if element is in array, or false if it is not):
isIncluded = arrayIncludes(arrayToCheck, elementToSearch, true) ' or false for matching case
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.