[英]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.