Home > Articles > Programming > Windows Programming

This chapter is from the book

This chapter is from the book

Declaring and Typing Arrays

The use of arrays is integral to almost any programming task. JScript has always had a method for creating arrays that can perform any task, but JScript arrays were never very efficient. The new arrays available through JScript .NET, which can exist side-by-side with JScript arrays, offer both performance and flexibility, but never both at the same time.

Declaring JScript and JScript .NET Arrays

The first step in working with arrays is to declare the array. Let's start by declaring a traditional JScript-style array:

var _JScriptArray:Array = new Array();
_JScriptArray[0] = "123";
_JScriptArray[2000] = 123;
_JScriptArray[500] = new Object();

The type of this array is Array, and the example creates a new instance of the Array class. Note that all the assignments in this example are valid, and that JScript-style arrays are not strongly typed. Everything that goes in the array is of type Object, and everything that comes out is of type Object. Therefore, you can assign a String object to array index 0, int to array index 2000, and new Object to array index 500.

JScript arrays are not bounded. New elements can be assigned on-the-fly. As you make assignments, a length function is updated so that the upper bounds of the array are always known. This comes in handy when you retrieve a JScript array and need to iterate over the contents. If some of the intermediate values were null, then you wouldn't be able to tell the end of the array without the length function. JScript arrays are extremely powerful, but there are some performance tradeoffs involved with them.

The following example demonstrates a variety of methods for finding the true 
end of a JScript array. The first method searches for null:var 
_JScriptArray:Array = new Array();
var _int:int = 0;

// Use JScript array like a stack
_JScriptArray[_int++] = "First Element";
_JScriptArray[_int++] = "Second Element";

// Now let's pass this off to a function that doesn't know its length
DumpArray(_JScriptArray);

function DumpArray(_jsArray:Array) {
    var _i:int = 0;
    while(_jsArray[_i]) {
        Console.WriteLine(_jsArray[_i]);
        _i++;
    }
}

This isn't very great code. You need to have a handle on what the top of the array is at all times so that you can add elements on the end. Then you have to search for null. Furthermore, if you put an element at index 10, then the print function would miss it because this function stops at the first null. You could also do better with the length function, and you could take advantage of a couple other functions in the process. For example, the push function allows you to put values on the end of an array and increment the length pointer accordingly, and the pop function returns the very last element of the array, removes it from the end, and decrements the length pointer accordingly. You could rewrite the preceding example as follows:

var _JScriptArray:Array = new Array();

// Use JScript array like a stack
JScriptArray.push("First Element", "Second Element");
JScriptArray[9] = "Tenth Element";

// Now let's pass this off to a function that doesn't know its length
DumpArray(_JScriptArray);

function DumpArray(_jsArray:Array) {
    for ( var _i = 0; i < _jsArray.length(); _i++ ) {
        Console.WriteLine(_jsArray[i]);
    }
}

This code performs the same operations as the preceding example, but it isn't as error prone. After popping the 2 items on the stack, the 3rd through 9th elements are left unassigned, and the 10th value is assigned. The array dynamically sizes to 10 elements as soon as the 10th element is set. The DumpArray function won't stop after the second value and will proceed right through the null elements to element 10 and print the contents.

An important feature of JScript-style arrays is that they are sparse arrays, which means the elements don't have to be contiguous. In the first example you set elements 0, 500, and 2000. Memory isn't allocated for any other elements besides these three, but this introduces a few problems. For instance, the DumpArray function would try to iterate through 2,000 elements, just to print 3 of them. This isn't extremely efficient. CLR-style arrays provide better performance than this, and the next section covers them in detail.

Using CLR-Style Arrays

A CLR-style array has bounds and a definite length, so it can't be expanded and shrunk on-the-fly. This type of array is also strongly typed, meaning you get both compiler and runtime errors for performing incorrect assignments. Every element that comes out of a CLR-style array is of a specific type, so you don't have to check for types before casting. The following example creates a CLR-style array of String objects in JScript .NET. The type is a null array type, and the new keyword is used with a bounded array type to fully initialize the variable:

var _CLRArray:String[] = new String[10];

// We now have a CLR array of Strings with 10 elements
_CLRArray[0] = "Hello";
_CLRArray[9] = "World";
_CLRArray[10] = "Produces an error";  // IndexOutOfRangeException

This array is now strongly typed to String objects. If you attempt to assign any other type of variable (for example, an integer), either the object in question is cast to a String object or you get an InvalidCast error. All objects support the ToString() function, so you will almost never see an InvalidCast error when assigning objects or values to a String array. This can cause very unexpected results. To get an error by assigning an incorrect type, you need to change to another type of array. For example, you could use an array of Int32 objects, such as the following:

var _CLRArray:Int32[] = new Int32[10];

_CLRArray[0] = 1;
// This works because the string can be parsed as a number_CLRArray[1] = "123";  
_CLRArray[2] = "Hello"; // This fails

With this code, you get a compiler error on the third assignment. It's a basic type mismatch because the compiler knows "Hello" cannot be converted to or parsed as an Int32 object. A number of other array types will also fail when values can't be converted to or from the appropriate type.

You need to be aware that CLR arrays don't have any of the functions you have seen previously in the JScript arrays. You can't push and pop values onto and off arrays, they aren't sparse, and you can't expand them at will. They do have some other properties, though. By using the Length property, you can determine the number of elements in an array. You can use the CopyTo function to transfer array contents from one array to another. You can use the Rank property to determine the number of dimensions an array contains. Take a look at Listing 3.4, which demonstrates the use of the Length property and the CopyTo function.

Listing 3.4  Dynamically Sizing Fixed Arrays

import System;

var _WorkArray:Int32[] = new Int32[10];
var _WorkOffset:Int32 = 0;
var _CopyArray:Int32[];

while(_WorkOffset < 50) {
    while(_WorkOffset < _WorkArray.Length) {
        _WorkArray[_WorkOffset] = _WorkOffset;
        _WorkOffset++;
    }
    
    if ( _WorkArray.Length < 50 ) {
        _CopyArray = new Int32[_WorkArray.Length + 10];
        _WorkArray.CopyTo(_CopyArray, 0);
        _WorkArray = _CopyArray;
        Console.WriteLine("Expanded Array to " + _WorkArray.Length);
    }
}

_WorkOffset = 0;
while(_WorkOffset < _WorkArray.Length) {
    Console.WriteLine(_WorkArray[_WorkOffset]);
    _WorkOffset++;
}

Listing 3.4 might seem to be quite a bit of code this early in the book. After all, you have not been introduced to while loops, conditional statements, and a number of other features that are used in this listing. So let's walk through the most important parts of Listing 3.4. First, it creates two arrays of type Int32. The work array is given bounds of 10. The copy array is not bounded and remains uninitialized until you fill up the work array. At this point, the copy array is declared to have bounds 10 greater than the work array, the contents of the work array is copied to the copy array, and the copy array is assigned to the work array so that work can continue.

You'll learn more about CLR-style arrays in the sections "Typing Arrays for Performance" and "Multidimensional Array Support" later in this chapter.

Typing Arrays for Performance

JScript-style arrays are slow because they aren't strongly typed. When you get an element in an array that isn't typed, you have no idea what kind of object you're getting. It could be a string, a hashtable, another array, or even a number. You just don't know, and neither does the computer. Therefore, you need code to do type checks and appropriate conversions before the value can be used.

CLR arrays are always typed. In order to create an instance of an array, the underlying type must be given first. Typed arrays can be created in two manners. Earlier in this chapter we talked about the language-specific manner of creating a typed array, which involves using a null array type to which you can later assign bounds by creating a new instance of a typed array. Another method is to create a variable of type System.Array. Later, you can assign it a typed array by using the System.Array.CreateInstance function. This method is extremely powerful because the type of array can be decided at runtime; however, this method also increases the chance of runtime exceptions because array assignments can't be typed and checked during compilation. The following example shows how to use both of these methods of creating typed arrays:

import System;

var _IntegerArray:Int32[] = new Int32[10];
var _StringArray:String[] = new String[10];
var _GenericArray:System.Array;

_GenericArray = _IntegerArray; //Success!
_GenericArray = _StringArray; //Success!

_GenericArray = System.Array.CreateInstance(
    Type.GetType("System.String,mscorlib"),
    10);

TIP

A generic CLR array has to be declared by using type System.Array. JScript interprets Array to mean a JScript array, even if the import System directive is present. This is for legacy purposes and prevents users from typing Microsoft.JScript.Array.

Note several neat things in the preceding example. First, you have two typed arrays that give maximum performance to the application. But you can also assign these arrays to the _GenericArray variable because it is of type System.Array, and all typed arrays inherit from this base class. (You'll learn more about inheritance in Chapters 6 and 7, "Interfaces and Class Members.") _GenericArray can be of any array type, but regardless of type, it has the performance of a typed array, without the compile-time warnings that would exist if you made a poor assignment to an array element. Notice that this example uses a special function on the System.Array class to create a String array. This looks pretty ugly, because it involves several levels of function calls, but it shows that arrays can be created with indeterminate types at runtime. In the example, you have to know the type of the Int32 and the String arrays, but you could have created any type of array by using the CreateInstance function. You can also create arrays that have a variable number of dimensions, as discussed in the following section.

Multidimensional Array Support

JScript .NET supports two types of multidimensional arrays. The first type is a standard equal-bounds array, in which all rows in the array are of the same length. The second type of array is a staggered array, which can have rows of different lengths. Staggered arrays can be effective when you're creating arrays in which some rows might have thousands of elements whereas other rows may contain very few or no elements.

Let's look first at the most common type of array, the equal-bounds array. In the type specifier for this array, you simply add one comma between the brackets for each additional dimension you need to introduce. In the new expression, you provide the bounds for each of the dimensions. This syntax makes creating a multidimensional array very easy. The following code demonstrates the creation of a 10-by-10 array, whose elements you initialize to create a multiplication table:

import System;

var myArray:Int32[,] = new Int32[10,10];
var i:int;
var j:int;

for(i = 0; i < 10; i++){
    for(j = 0; j < 10; j++){
        myArray[i,j] = (i+1)*(j+1);
    }
}

TIP

An overloaded method of Array.CreateInstance allows for the creation of multidimensional arrays as well, and it is often useful when you're creating an array of a type that is not yet known or when the user can specify the number of dimensions (which might be the case with some math applications).

To use this array, you index the array by using an offset for each dimension of the array. You can continue adding offsets for any number of additional dimensions.

NOTE

Although JScript supports a staggered array, we don't examine the syntax here. It's rather difficult to work with staggered arrays, and there are very few cases in which they are useful and necessary.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020