Creation Methods of the Array Object
The Array object contains three methods that let you build key-value maps on the fly.
Based on user input, Vijaye instead built square bracket operators and they store the arrays in an encoded format in the string primitive. That is the recommended way to create arrays.
But let's still explore these methods since they exist and it's a good study of the different methodologies.
In this example, you’re going to store the prices of video game systems. Start by typing the code in the Listing.
Listing: Building dynamic arrays
1 ' DynamicArrays.sb
2 Array.SetValue("price", "Xbox", 95)
3 Array.SetValue("price", "Wii", 75)
4 Array.SetValue("price", "Playstation", 85)
This code uses the SetValue() method of the Array object to create an associative array named "price". This array has three keys ("Xbox", "Wii", and "Playstation") and their prices. Note that the name of the array (the first argument) is a string enclosed between double quotes. This is different from the other methods of the Array object you used earlier, which need an array’s identifier as an argument.
Since the prices of video game systems change, you’ll want to update your information. You can use the SetValue() call on an existing element and the new value replaces the old one!
Now, let’s look up some video game system prices. Add the following code to the Listing and run it to see what you get.
p1 = Array.GetValue("price", "Xbox") ' Returns 95
p2 = Array.GetValue("price", "xbox") ' Empty
p3 = Array.GetValue("price", "3DS") ' Empty
TextWindow.WriteLine("p1 = " + p1)
TextWindow.WriteLine("p2 = " + p2)
TextWindow.WriteLine("p3 = " + p3)
The GetValue() method returns the value associated with its index. The first argument’s the name of the array. Here’s the output of running this code:
p1 = 95
The first statement returns 95 for the price of "Xbox". But why didn’t p2 return 95 when you pass "xbox" as the search key? In this case, the search is case sensitive! Our array doesn’t have a key for 3DS, so the third statement returns an empty string.
You can use the RemoveValue() method remove any item from the associative array. Add the following code to the program to learn how this method works:
p4 = Array.GetValue("price", "Xbox") ' Empty
TextWindow.WriteLine("p4 = " + p4)
The first statement removes the Xbox key (and its price) from the "price" array. When you look up the price of Xbox in the second statement, the GetValue() method returns an empty string, because you removed this key from the table.
Now that you know an alternate way to create arrays, here are some reasons why you shouldn't mix the array types: Small Basic - Array Mix.
Do you have any questions? Ask us! We're full of answers and other fine things!
Head to the Small Basic forum to get the most answers to your questions:
And go to http://blogs.msdn.com/SmallBasic to download Small Basic and learn all about it!
Small and Basically yours,
- Ninja Ed & Majed Marji