簡體   English   中英

VBScript函數可以返回字典嗎?

[英]Can a VBScript function return a dictionary?

我有一個表單數據字典,我想用函數修改。

function queryCleanForm(myDictForm)

    dim arrayKeys
    arrayKeys = myDictForm.keys

    for i=0 to myDictForm.count-1
        myDictForm(arrayKeys(i)) = replace(myDictForm(arrayKeys(i)), "'", "''")
        response.write myDictForm(arrayKeys(i))
    next

    queryCleanForm = myDictForm
end function

問題是行queryCleanForm = myDictForm錯誤為

Wrong number of arguments or invalid property assignment 

有沒有辦法在VBScript中執行此操作?

試試這個:

SET queryCleanForm = myDictForm

對於對象,您需要使用SET告訴VBScript它是一個對象引用,而不是賦值類型。

是的,您需要使用SET命令:

設置queryCleanForm = myDictForm

您還可以在函數中使用ByRef或ByVal值。 ByVal,您發送給函數或子函數的對象被復制到私有內存中以在函數內部使用,並在函數完成后丟棄。 ByRef,您發送給函數的對象被引用,您所做的所有操作,刪除鍵,設置對象等都直接對您發送的對象進行。

例如

Sub test
   DIM testDict as variant
   call setdict(testDict)

   testDict.Add "test", "value" 

   call addValue(testDict, "test2","another value")

   msgbox testDict.Count

   Set testDict = Nothing
End Sub

Sub setdict(ByRef in_Dict as Variant)
  If Typename(in_Dict) <> "Dictionary" Then
    SET in_Dict  = CreateObject("Scripting.Dictionary")
  end if
end sub

sub addValue(ByRef in_Obj as Variant, ByVal in_Key as String, ByVal in_Value as String)
 if not in_Obj.Exists(in_Key) then
     in_Obj.Add in_Key, in_Value
 end if
end sub

測試子調用變量類型變量到子setdict。 在函數中,我驗證發送給sub的對象的類型。 如果對象類型不是字典對象(它不是),那么實際上在子測試中聲明的testDict對象的對象in_Dict將被設置為字典對象。

為了更好地演示參考,我還包括了第二個名為addvalue的子。 我再次將對象作為引用傳遞給函數,並將另一個鍵添加到字典對象中。 在主要測試sub ill然后發布計數。 在這種情況下,存在2個鍵。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM