|Home | Tutorial | Classes | Functions | QSA Workbench | Language | Qt API | QSA Articles Qt Script for Applications

[Prev: Built-in Types] [Home] [Next: Boolean]

Array

An Array is a datatype which contains a named list of items. The items can be any Qt Script object. Multi-dimensional arrays are achieved by setting array items to be arrays themselves.

Arrays can be extended dynamically simply by creating items at non-existent index positions. Items can also be added using push(), unshift() and splice(). Arrays can be concatenated together using concat(). Items can be extracted using pop(), shift() and slice(). Items can be deleted using splice(). Arrays can be turned into strings using join() or Array::toString(). Use reverse() to reverse the items in an array, and sort() to sort the items. The sort() function can be passed a comparison function for customized sort orders.

In general, operations that copy array items perform a deep copy on items that are Number or String objects, and a shallow copy on other objects.

Array Construction

Arrays can be constructed from array literals or using the new operator:

    var mammals = [ "human", "dolphin", "elephant", "monkey" ];
    var plants = new Array( "flower", "tree", "shrub" );
    var things = [];
    for ( i = 0; i < mammals.length; i++ ) {
        things[i] = new Array( 2 );
        things[i][0] = mammals[i];
        things[i][1] = plants[i];       
    }

Arrays can be initialized with a size, but with all items undefined:

    var a = new Array( 10 ); // 10 items
Array Access

Array items are accessed via their names. Names can be either integers or strings.

Example:

    var m2 = mammals[2];
    mammals[2] = "gorilla";
    var thing = things[2][1]

The first statement retrieves the value of the third item of the mammals array and assigns it to m2, which now contains "monkey". The second statement replaces the third item of the mammals array with the value "gorilla". The third statement retrieves the second item of the third item's array from the things array and assigns it to thing, which now contains "shrub".

As stated above, it is also possible to access the arrays using strings. These act as normal properties, and can be accessed either using the square bracked operator ([]) or by directly dereferencing the array object and specifying the property name (.name). These two accessor types can be mixed freely as seen below with the address and phoneNumber properties.

    var names = [];
    names["first"] = "John";
    names["last"] = "Doe";
    var firstName = names["first"];
    var lastName = names["last"];
   
    names["address"] = "Somewhere street 2";
    names.phoneNumber = "+0123456789";
    var address = names.address;
    var phoneNumber = names["phoneNumber"];
Array Properties
Array Functions