Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New to the CF scene
    Join Date
    Feb 2007
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Question Multidimensional array element overwriting

    Hey,

    Im new to javascript but i'm an experienced programmer, im having a problem with a 2 dimensional array where assigning to additional elements overwrites all elements. I suspect theres an easy fix or that im just missing a language fundamental. Heres the source code of the problem as simple as i could make it. cut paste into html and it works. Any help would be appreciated.

    Code:
    <script>
    
    var creditAmounts = new Array();
    
    for (i=0;i<2;i++)
    {
    	alert("I :: " + i);
    	creditAmounts[i] = new Array();
    	creditAmounts[i,0] = "creditAmount"+i;
    	creditAmounts[i,1] = i;
    	
    }
    document.write( "[0][0]: " + creditAmounts[0,0] + "<br>");
    document.write( "[0][1]: " + creditAmounts[0,1] + "<br>");
    document.write( "[1][0]: " + creditAmounts[1,0] + "<br>");
    document.write( "[1][1]: " + creditAmounts[1,1] + "<br>");
    </script>
    Running the script results in [0][0] and [1][0] having the same value...

  • #2
    Senior Coder
    Join Date
    Mar 2005
    Location
    Portsmouth UK
    Posts
    4,511
    Thanks
    3
    Thanked 504 Times in 491 Posts
    var creditAmounts = new Array();
    Code:
    for (i=0;i<2;i++){
     creditAmounts[i] = new Array();
     creditAmounts[i][0] = "creditAmount"+i;
     creditAmounts[i][1] = i;
    
    }
    
    or
    
    var creditAmounts = [];
    
    for (i=0;i<2;i++){
     creditAmounts[i]= ["creditAmount"+i,i];
    }
    Vic

    God Loves You and will never love you less.

    http://www.vicsjavascripts.org/Home.htm

    If my post has been useful please donate to http://www.operationsmile.org.uk/

  • #3
    New to the CF scene
    Join Date
    Feb 2007
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Hey thanks,

    I really should have double checked the syntax on that one, i was just referencing from another post i saw. That'll teach me. :P


  •  

    Posting Permissions

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