Forum Discussion

yurik's avatar
yurik
Contributor
9 years ago

How to create a list or variable length array of objects?

Hi,

  I'm trying to create a list of objects to be returned from a function, but I can't make it work.

  The following function works fine

 

function xxxxxxx()

{

    var ContactRow = Aliases["FullScreenApplication"]["AllContactsGrid"]["AllContactsGridView"]("RowControl", "", 1);

    var RowIndex = 1;

    var ContactsList = new Array(4);

    do

    {

          ContactsList[RowIndex - 1] = ContactRow["DataContext"]["Row"];

          RowIndex++;

     if(RowIndex <= Aliases["FullScreenApplication"]["AllContactsGrid"]["wRowCount"])

         ContactRow = Aliases["FullScreenApplication"]["AllContactsGrid"]["AllContactsGridView"]("RowControl", "", RowIndex);

          else

                 ContactRow = null;

    }

     while(ContactRow != null )

 

return ContactsList;

 

}

 

In this example I'm creating an Array of 4 objects. 

 

My question is how to create a List or an ArrayList or an Array of variable length ? Each element of the array is an Object (not a string or any other single value)

 

 

Thank you!

    Yuri

 

 

P.S.

   I'm using TC 10.6

  • HKosova's avatar
    HKosova
    SmartBear Alumni (Retired)

    Hi Yuri,

     

    You can use the Array.push method to add elements to an aray dynamically:

    var arr = []; // empty array
    for (var i = 0; i < 5; i++)
      arr.push(i);
    
    Log.Message(arr.length); // 5
    • Colin_McCrae's avatar
      Colin_McCrae
      Community Hero

      ^^^

       

      Except that the (hard coded) loop length defines the array size in the above example.

       

      So doing it dynamically is pointless. As you already know in advance it will be 5.

       

      (Handy to know nonetheless as I assume it will be the same in C# Script .... which is what I'm currently using/learning as I go)

       

      Much like the OP where the RowCount can be retrieved and known before the array is declared so dynamic declaration should not be required?

      • HKosova's avatar
        HKosova
        SmartBear Alumni (Retired)

        It was just an example to illustrate the idea of dynamic array initialization. JavaScript/JScript arrays are dynamic by design, you can add and remove array elements at any time.

        var arr = [];
        while (condition) {
          arr.push(element)
        }
        
        arr.pop(); // remove last element
        
        arr.splice(3, 1); // remove 1 element at index 3

        Reference: JScript Array object

  • Is it not just a case of getting a row count before you start and using that to define the size of the array?

     

    I'm a VBScript guy. I know how to dynamically re-size arrays in that. But not in jScript I'm afraid. Although, if you know the array size in advance, this shouldn't be required.