Array Keys VBSCRIPT

I am new to vbscript and I am struggling a bit as I am more familiar with Javascript. Can someone please give me a hand?

Does vbscript support using named array keys, as I have in my example below?

For example, I have:

Dim result(3) result(age) = 60 result(firstname) = "Tony" result(height) = 187 result(weight) = 76 msgbox("Age: " & result(age) & vbCr &_ "Name: " & result(firstname) & vbCr &_ "Height: " & result(height) & vbCr &_ "Weight: " & result(weight) ) 

The resulting msgbox shows:

  Age: 76 Name: 76 Height: 76 Weight: 76 

It seems that each element of the result array is set to 76, which should only be assigned to the "weight" element.

Is this because vbscript only accepts integers as a key / index for arrays?

Any help is appreciated.

Thanks Turgs

+4
source share
3 answers

In addition to the Andrew solution on this page, I was able to use the Dictionary object in VBScript to do what happened after using a syntax more similar to the Normal Use Associative Arrays in other languages:

 Dim result Set result = CreateObject("scripting.dictionary") result("age") = 60 result("firstname") = "Tony" result("height") = 187 result("weight") = 76 msgbox("Age: " & result("age") & vbCr &_ "First Name: " & result("firstname") & vbCr &_ "Height: " & result("height") & vbCr &_ "Weight: " & result("weight") ) 

More information about the dictionary object can be found here: http://www.microsoft.com/technet/scriptcenter/guide/sas_scr_ildk.mspx

I hope this helps others trying to do the same.

Thanks to Richard Mueller for providing this solution through the Usenet group microsoft.sublic.scripting.vbscript.

Greetings

Turgs

+6
source

To achieve this, you need to use the Dictionary object from the Scripting library: -

 Dim result : Set result = CreateObject("Scripting.Dictionary") result.Add "Age", 60 result.Add "Name", "Tony" 

etc. You can get items as: -

 Dim age : age = result("Age") 

However, if you have a fixed set of identifiers, you can consider a class definition: -

 Class CResult Public Age Public Name End Class Dim result : Set result = new CResult result.Age = 60 result.Name = "Tony" MsgBox "Age: " & result.Age & vbCrLf & _ "Name: " & result.Nname) & vbCrLf 

By the way, we usually use CR LF for newlines, not just CR. Also, if you use a method or function as an instruction (as in MsgBox above), do not include parameters in ().

+9
source

No VBScript allows only an integer index. In doing so, you can declare integer constants to deliver the desired functionality.

If you need a named array (like the example above), you probably need some kind of dictionary.

0
source

All Articles