www.webdeveloper.com
Results 1 to 4 of 4

Thread: Elements in an array?

  1. #1
    Join Date
    Dec 2005
    Posts
    15

    Elements in an array?

    I have the following array setup

    Code:
    function Franchise (id, name) {
       this.id = id;
       this.name = name;
    }
     
    var franchiseDatabase = new Array();
    franchiseDatabase['fid_0000'] = new Franchise('0000', 'Team 0');
    franchiseDatabase['fid_0001'] = new Franchise('0001', 'Team 1');
    franchiseDatabase['fid_0002'] = new Franchise('0002', 'Team 2');
    franchiseDatabase['fid_0003'] = new Franchise('0003', 'Team 3');


    I need to figure out the number of elements in franchiseDatabase


    alert(franchiseDatabase.length) returns 0 when I thought it should return 4.



    What is the proper way to count the # elements for franchiseDatabase if the array is set up like I have above?

  2. #2
    Join Date
    May 2003
    Location
    Between Baltimore and DC
    Posts
    3,579
    Confusing as it is you have an associative arrays which is not an array at all, they are just complex objects. That means you have no length property to work with. Only way to know how many you have is to loop through it and count.

    Code:
    var cnt = 0;
    for(var x in franchiseDatabase)cnt++;
    Eric
    Tech Author [Ajax In Action, JavaScript: Visual Blueprint] | twitter | linkedin | http://www.pascarello.com

  3. #3
    Join Date
    Dec 2005
    Posts
    15
    Thank you very much.

  4. #4
    Join Date
    Jul 2010
    Posts
    135
    :-)

    Code:
    function Franchise (id, name) {
       this.id = id;
       this.name = name;
    }
    function AddRec (id, name) {
       franchiseDatabase['fid_'+id] = new Franchise(id, name);
       franchiseDatabase.length++;
       alert(franchiseDatabase.length);
    }
    
     
    var franchiseDatabase = new Array();
    AddRec('0000', 'Team 0');
    AddRec('0001', 'Team 1');
    AddRec('0002', 'Team 2');
    AddRec('0003', 'Team 3');

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles